How do I create/post a new managed object to serve

2019-05-02 10:35发布

问题:

I'm having a very hard time finding documentation or examples of creating a new managed object, setting it's values, and saving to the server using Restkit.

I have a NSManagedObject Post:

@interface Post : NSManagedObject

@property (nonatomic, retain) NSNumber * postID;
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * text;

@end

This is my AppDelegate Setup:

// ---- BEGIN RestKit setup -----
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);

NSError *error = nil;
NSURL *modelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"My_App" ofType:@"momd"]];
// NOTE: Due to an iOS 5 bug, the managed object model returned is immutable.
NSManagedObjectModel *managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] mutableCopy];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];

// Enable Activity Indicator Spinner
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

// Initialize the Core Data stack
[managedObjectStore createPersistentStoreCoordinator];

NSPersistentStore __unused *persistentStore = [managedObjectStore addInMemoryPersistentStore:&error];
NSAssert(persistentStore, @"Failed to add persistent store: %@", error);

[managedObjectStore createManagedObjectContexts];

// Configure a managed object cache to ensure we do not create duplicate objects
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];

// Set the default store shared instance
[RKManagedObjectStore setDefaultStore:managedObjectStore];

// Configure the object manager
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://localhost:3000/api/v1"]];
objectManager.managedObjectStore = managedObjectStore;
NSString *auth_token = [[LUKeychainAccess standardKeychainAccess] stringForKey:@"auth_token"];  // Getting the Auth_Token from keychain
[objectManager.HTTPClient  setAuthorizationHeaderWithToken:auth_token];

[RKObjectManager setSharedManager:objectManager];

// Setup Post entity mappping
RKEntityMapping *postMapping = [RKEntityMapping mappingForEntityForName:@"Post" inManagedObjectStore:managedObjectStore];
[postMapping addAttributeMappingsFromDictionary:@{
 @"title":             @"title",
 @"text":       @"text",
 @"id":         @"postID"}];

RKResponseDescriptor *postResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:postMapping pathPattern:nil keyPath:@"post" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:postResponseDescriptor];

Now, In my NewPostViewController when I click my "Save" button I have in my navbar, what do I need to do to save this post to my server?

Here's what I've tried, but it's not working correctly. I enter the success block and my server got the POST, but the fields are nil:

- (void)savePost {
    RKManagedObjectStore *objectStore = [[RKObjectManager sharedManager] managedObjectStore];
    Post *post = [NSEntityDescription insertNewObjectForEntityForName:@"Post" inManagedObjectContext:objectStore.mainQueueManagedObjectContext];
    [post setTitle:@"The Title"];
    [post setText:@"The Text"];

    [[RKObjectManager sharedManager] postObject:post path:@"posts" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
        NSLog(@"Success saving post");
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        NSLog(@"Failure saving post: %@", error.localizedDescription);
    }];
}

回答1:

It looks like you haven't added any RKRequestDescriptor's to your object manager. Without them, the poor object manager can't use key/value magic to serialize your object into an NSDictionary.

The thing that you HAVE added, the RKResponseDescriptor, describes how responses are managed. That's why you're seeing the success block called: RestKit has no idea what you're trying to send, but it recognizes the Post objects in the server response.

Try adding this below your responseDescriptor code:

RKRequestDescriptor * requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[postMapping inverseMapping] objectClass:[Post class] rootKeyPath:@"post"];
[objectManager addRequestDescriptor:requestDescriptor];

(double check the keypath; I don't know what your API expects, so I went with what you had in the response descriptor)