【问题标题】:Core data only storing last object of JSON feed核心数据仅存储 JSON 提要的最后一个对象
【发布时间】: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


【解决方案1】:

有多少节目?您可以通过以下操作找到此内容:NSLog(@"Number of shows: %d.", shows.count);,假设显示是 NSArray。可能是您的 Core Data 代码没有问题,而 JSON 解析本身有问题。

编辑:另外,您是否正确地将更改保存到持久存储?

【讨论】:

  • 显示次数为 42。正确将更改保存到持久存储是什么意思?
【解决方案2】:

通常当您看到这样保存的几个对象中的一个时,问题是应该是对多的关系被错误地设置为对一。无论您尝试向关系中添加多少对象,都只会设置最后一个,因为关系只能保存一个值。

我认为在这种情况下,问题很可能出在自定义子类的代码中,而不是数据模型本身,因为数据模型适用于通用 NSManagedObjects。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多