gpt4 book ai didi

iphone - 如何使用 Core Data 加快将新对象插入实体的速度

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:00:11 24 4
gpt4 key购买 nike

这是我的代码,它获取一些 JSON 数据并将其插入核心数据室实体:

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]);
}
}

插入大约 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]);
}

关于iphone - 如何使用 Core Data 加快将新对象插入实体的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7335509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com