0

我有一个 JSON 响应,我把它变成了这样的字典:

NSError *error;
self.restKitResponseDict = [NSDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:response.body options:0 error:&error]];

我有一个具有以下属性/属性的核心数据类:

name
image_url

当我restKitResponseDict从上面记录时,我看到它image_url被列为"image_url"如下:

name = Rock;
"image_url" = "http://f.cl.ly/items/122s3f1M1E1p432B211Q/catstronaut.jpg";

这就是KVC崩溃的原因吗

[CoreDataClass setValuesForKeysWithDictionary:self.restKitResponseDict];

像这样:

'[<CoreDataClass 0x14132c> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key image_url.'

引号重要吗?我应该要求我的服务器人员摆脱可能导致它的下划线吗?

核心数据类:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface CoreDataClass : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * image_url;

@end

@implementation CoreDataClass

@dynamic name;
@dynamic image_url;

@end
4

2 回答 2

1

NSLog()with%@格式使用该方法description打印对象,并且 a 的描述NSDictionary将包含任何特殊字符(例如下划线)的所有键和值放在引号中。例如

NSDictionary *dict = @{
    @"key1" : @"value_1",
    @"key_2" : @"value2"
};
NSLog(@"dict=%@", dict);

生产

2012-08-25 18:15:33.553 test27[3416:c07] dict={
    key1 = "value_1";
    "key_2" = value2;
}

因此,您的 JSON 字典中的键实际上没有引号,并且下划线可能不是错误的原因。

错误消息表明托管对象没有属性image_url,因此您应该检查它。

于 2012-08-25T16:19:49.057 回答
1

您正在将方法发送到类对象:

[CoreDataClass setValuesForKeysWithDictionary:self.restKitResponseDict];

当您可能想将其发送到实际的 CoreDataClass 实例时:

[coreDataClassObject setValuesForKeysWithDictionary:self.restKitResponseDict];

编辑

从类中初始化对象的最简单方法是什么?– 埃里克

它是 NSManagedObject 的子类,因此您可以使用普通的 Core Data 方法。创建新对象的一种方法:

CoreDataClass *coreDataObject = [NSEntityDescription
    insertNewObjectForEntityForName:@"YOUR_ENTITY_NAME"
    inManagedObjectContext:managedObjectContext];

如果您需要有关使用核心数据的基本信息,请参阅核心数据编程指南:http: //developer.apple.com/library/ios/#documentation/cocoa/conceptual/coredata/cdProgrammingGuide.html#//apple_ref/doc/ uid/TP30001200-SW1

于 2012-08-26T14:58:17.827 回答