【发布时间】:2011-09-20 11:28:08
【问题描述】:
我在我的应用程序中使用 Core Data 作为本地存储。我已经正确设置并为每个实体创建了 NSManagedObject 的子类。但是,当我尝试将值插入我的商店时,它只会插入我的 JSON 提要中的最后一个对象。
res = [JSONHandler requestJSONResponse:jsonString];
shows = [res valueForKeyPath:@"Show.Name"];
NSUInteger showIndex = 0;
for(NSString *showName in shows){
showObject = [NSEntityDescription insertNewObjectForEntityForName:@"Show" inManagedObjectContext:managedObjectContext_];
showObject.name = showName;
showObject.iD = [[res valueForKeyPath:@"Show.Id"]objectAtIndex:showIndex];
showObject.desc = [[res valueForKeyPath:@"Show.Description"]objectAtIndex:showIndex];
showObject.activityType = [[res valueForKeyPath:@"Show.ActivityType"]objectAtIndex:showIndex];
showIndex++;
}
这仅存储我的 JSON 提要中的最后一个对象。知道为什么吗?
编辑:当我这样做时效果很好:
res = [JSONHandler requestJSONResponse:jsonString];
shows = [res valueForKeyPath:@"Show.Name"];
NSUInteger index = 0;
for(NSString *showName in shows){
show = [NSEntityDescription insertNewObjectForEntityForName:@"Show" inManagedObjectContext:managedObjectContext_];
[show setValue:showName forKey:@"name"];
[show setValue:[[res valueForKeyPath:@"Show.Id"]objectAtIndex:index] forKey:@"iD"];
[show setValue:[[res valueForKeyPath:@"Show.Description"]objectAtIndex:index] forKey:@"desc"];
[show setValue:[[res valueForKeyPath:@"Show.ActivityType"]objectAtIndex:index] forKey:@"activityType"];
index++;
}
基本上是一样的,不是吗?但我想使用 NSManagedObject 的子类,而不是像上面那样做。因为在上面的 sn-p 中显示的是 NSManagedObject *show 而不是它应该是的:Show *show。
【问题讨论】:
-
JSON 看起来如何?
NSLog(@"Shows: %@", shows);的结果是什么? -
我 100% 确定 JSON 没问题。
-
如果添加演员阵容会怎样?
showObject = (Show *)[NSEntityDescription insertNewObjectForEntityForName:@"Show" inManagedObjectContext:managedObjectContext_];
标签: iphone objective-c xcode json core-data