开发者

Why isn't my data getting saved in Core Data?

I am trying to save multiple rows into my coredata database using the following code. It only saves the last row. Why is it doing that?

nsManagedObject1.column1 = @"First row";
nsManagedObject1开发者_运维百科.column2 = @"Test 2";

//insert first row
if (![context save:&error]) {
    NSLog(@"Could not save the data: %@",[error localizedDescription]);
}

//insert second row
nsManagedObject1.column1 = @"Second row";
nsManagedObject1.column2 = @"Test 2";

if (![context save:&error]) {
    NSLog(@"Could not save the data: %@",[error localizedDescription]);
}

//see how many rows exist in the database
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"TestDB" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSLog(@"Number of rows: %d",[fetchedObjects count]);

In the count, I get only one row. When I print the data in the rows, it only finds the last row that I entered into the database. Why is it doing that? Since I did save on the context, I was expecting the two rows to be available in the database. Please help! I also do not get any errors.

PS - I know that I should not be doing this but I feel that I should understand why all the rows are NOT getting saved.


Two have two rows you need two managed objects. All you are doing here:

//insert second row
nsManagedObject1.column1 = @"Second row";
nsManagedObject1.column2 = @"Test 2";

is updating nsManagedObject1's column1 and column2 to have new values.

You need to create a nsManagedObject2, and that will give you two rows in the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜