如何使用Restkit 0.20.0创建/发布新的托管对象到服务器? [英] How do I create/post a new managed object to server using Restkit 0.20.0?

查看:178
本文介绍了如何使用Restkit 0.20.0创建/发布新的托管对象到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到创建新的托管对象,设置其值,并使用Restkit保存到服务器的文档或示例。

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.

我有一个NSManagedObject文章:

I have a NSManagedObject Post:

@interface Post : NSManagedObject

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

@end

这是我的AppDelegate设置:

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];

现在,在我的NewPostViewController中,当我单击我的保存按钮时,我需要做这件事,以保存到我的服务器?

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?

这是我试过,但它不能正常工作。我进入成功块,我的服务器得到了POST,但字段是nil:

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);
    }];
}


推荐答案

t添加任何RKRequestDescriptor到你的对象管理器。没有他们,穷人的对象管理器不能使用键/值魔术来将你的对象序列化为NSDictionary。

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.

您已添加的东西RKResponseDescriptor描述了如何管理响应。这就是为什么你看到的成功块叫:RestKit不知道你试图发送,但它认识到Post对象在服务器响应。

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将其添加到您的responseDescriptor代码下面:

Try adding this below your responseDescriptor code:

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

(双击键值;我不知道你的API期望什么,你在响应描述符中)

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

这篇关于如何使用Restkit 0.20.0创建/发布新的托管对象到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆