只有数组中的最后一个对象插入到Core Data中

时间:2015-02-04 23:49:17

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

我试图将数据从数组插入到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文件,只检查了&#34; 3&#34;插入了。

1 个答案:

答案 0 :(得分: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
}