asl*_*kjd 2 iphone core-data objective-c ios
这是我的代码,它采用一些JSON数据并将其插入Core Data room实体:
for (NSDictionary *room in rooms)
{
NSDictionary *thisroom = [room objectForKey:@"room"];
NSString *roomidstring = [thisroom objectForKey:@"roomid"];
int roomid = [roomidstring intValue];
NSString *roomname = [thisroom objectForKey:@"roomname"];
NSString *buildingidstring = [thisroom objectForKey:@"buildingid"];
int buildingid = [buildingidstring intValue];
// import into database
NSManagedObject *roomInfo = [NSEntityDescription insertNewObjectForEntityForName:@"room" inManagedObjectContext:context];
[roomInfo setValue:[NSNumber numberWithInteger:roomid] forKey:@"roomid"];
[roomInfo setValue:roomname forKey:@"roomname"];
[roomInfo setValue:[NSNumber numberWithInteger:buildingid] forKey:@"buildingid"];
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
Run Code Online (Sandbox Code Playgroud)
插入约900个物体时速度极慢.有没有办法让这个更高效和/或加快速度?
谢谢!
是的,在完成循环之前不要保存,或者如果内存有问题则分批保存.保存操作非常昂贵,因此您应该避免经常在像这样的紧密循环中保存.
for (NSDictionary *room in rooms)
{
NSDictionary *thisroom = [room objectForKey:@"room"];
NSString *roomidstring = [thisroom objectForKey:@"roomid"];
int roomid = [roomidstring intValue];
NSString *roomname = [thisroom objectForKey:@"roomname"];
NSString *buildingidstring = [thisroom objectForKey:@"buildingid"];
int buildingid = [buildingidstring intValue];
// import into database
NSManagedObject *roomInfo = [NSEntityDescription insertNewObjectForEntityForName:@"room" inManagedObjectContext:context];
[roomInfo setValue:[NSNumber numberWithInteger:roomid] forKey:@"roomid"];
[roomInfo setValue:roomname forKey:@"roomname"];
[roomInfo setValue:[NSNumber numberWithInteger:buildingid] forKey:@"buildingid"];
}
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1000 次 |
| 最近记录: |