【问题标题】:How do I create/post a new managed object to server using Restkit 0.20.0?如何使用 Restkit 0.20.0 创建/发布新的托管对象到服务器?
【发布时间】:2013-03-23 05:24:24
【问题描述】:

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

我有一个 NSManagedObject 帖子:

@interface Post : NSManagedObject

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

@end

这是我的 AppDelegate 设置:

// ---- 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 中,当我单击导航栏中的“保存”按钮时,我需要做什么才能将此帖子保存到我的服务器?

这是我尝试过的,但它无法正常工作。我输入了成功块,我的服务器收到了 POST,但字段为零:

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

【问题讨论】:

  • 可以记录映射结果对象吗?
  • 我的服务器回复了新创建的帖子,但标题和文本都为零。检查我的 Rails 输出控制台,它收到 POST 请求,但文本和标题为零。
  • 您是否尝试过访问它们? CoreData 可能会延迟加载它。
  • 不确定你的意思。已发布的“帖子”将标题和文本字段的 nil 发送到服务器,因此我发布新对象的方式似乎存在问题。

标签: ios objective-c rest core-data restkit


【解决方案1】:

您似乎没有将任何 RKRequestDescriptor 添加到您的对象管理器中。没有它们,可怜的对象管理器就无法使用键/值魔法将您的对象序列化为 NSDictionary。

您添加的 RKResponseDescriptor 描述了如何管理响应。这就是为什么您会看到名为的成功块:RestKit 不知道您要发送什么,但它可以识别服务器响应中的 Post 对象。

尝试在您的 responseDescriptor 代码下方添加:

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

(仔细检查密钥路径;我不知道您的 API 期望什么,所以我选择了响应描述符中的内容)

【讨论】:

  • 正是我所缺少的,谢谢!但是我不能使用[postMapping inverseMapping],因为 id 字段被设置为 0,所以我创建了一个新的 requestDescriptor,将 id 字段排除在外。发布对象后,将在服务器上创建 ID。作为其中的一部分,我是否需要保存任何核心数据?返回响应是新创建的帖子,是否足够好?它匹配发布的 responseDescriptor...
  • 它的工作......!但是get请求中需要反向映射吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多