【问题标题】:Only last object in array being inserted into Core Data只有数组中的最后一个对象被插入到核心数据中
【发布时间】:2015-02-04 23:49:17
【问题描述】:

我正在尝试将数组中的数据插入 Core Data,但只有数组中的最后一个对象会进入数据库。

这是我的代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    _myArray = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil];
    [self addToCoreData];
}


-(void)addToCoreData {

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSError *error;
NSManagedObject *object;
object = [NSEntityDescription insertNewObjectForEntityForName:@"myEntity" inManagedObjectContext:context];

for (int x = 1; x < [_myArray count]; x++) {
    [object setValue:_myArray[x] forKey:@"name"];
}
[context save:&error];

[self fetchData]; //Puts data into UITableview
}

我检查了 SQLite 文件,只插入了“3”。

【问题讨论】:

  • 你只有一个 NSEntityDescription。因此只有一个值。

标签: ios objective-c iphone xcode core-data


【解决方案1】:

尝试将托管对象的创建移到循环中:

-(void)addToCoreData {

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = [appDelegate managedObjectContext];

     NSError *error;
     NSManagedObject *object;


    for (int x = 1; x < [_myArray count]; x++) {
        object = [NSEntityDescription    insertNewObjectForEntityForName:@"myEntity" inManagedObjectContext:context];
        [object setValue:_myArray[x] forKey:@"name"];
    }
    [context save:&error];

    [self fetchData]; //Puts data into UITableview
}

【讨论】:

  • 得到一个 SIGABRT: '[NSArrayM insertObject:atIndex:]: object cannot be nil'
  • 没关系,SIGABRT 部分无关,这解决了数组问题,干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
相关资源
最近更新 更多