gpt4 book ai didi

ios - 从 json 插入核心数据模型

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

我有一个服务来获取响应以下 json 的员工:

[{ "initials": "PR", "name": "Paul", "accounts": ["SPA", "ITA"] },  
{ "initials": "SR", "name": "William", "accounts": ["ITA"] } ]

和另一个获取帐户的服务,结果是这样的 json:

[{ "code": "SPA", "name": "Spain", "employees": ["PR"]  },
{ "code": "ITA", "name": "Italy", "employees": ["PR", "SR"] } ]

我需要解析接收到的信息并将其插入到具有两个核心数据模型的核心数据数据库中,雇员和帐户声明为多对多关系。它们声明如下:

@interface Employee : NSManagedObject

@property (nonatomic, retain) NSString *initials;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSSet *accounts;

@end

@interface Account : NSManagedObject

@property (nonatomic, retain) NSString *code;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSSet *employees;

@end

我现在正在做的是首先插入员工,然后创建每个帐户并查询要插入每个帐户的员工。显然,这样做的性能非常糟糕,因为我需要为每个帐户发出请求。

- (void)loadEmployeesJSON { ... }
- (void)loadAccountsJSON {
NSManagedObjectContext *context = self.managedObjectContext;

NSError *err = nil;
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"Accounts" ofType:@"json"];
NSArray *accounts = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath] options:kNilOptions error:&err];

[accounts enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
Account *account = [NSEntityDescription insertNewObjectForEntityForName:@"Account" inManagedObjectContext:context];
account.code = [obj objectForKey:@"code"];
account.name = [obj objectForKey:@"name"];
account.employees = [self accountsForEmployee:[obj objectForKey:@"employees"]];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
}

- (NSSet*)accountsForEmployee:(NSArray*)initialsArray {
NSManagedObjectContext *context = self.managedObjectContext;
NSError *error = nil;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:context];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"initials IN %@", initialsArray]];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
return [NSSet setWithArray:fetchedObjects];
}

如何在不请求每个帐户的员工的情况下链接它们?我以为我可以在内存中映射所有员工并请求他们。但是,如果我的员工数据库太大 (+100.000) 无法保存在内存中怎么办?

最佳答案

无论大小如何,您都可以将所有员工都放在内存中。为此,在创建员工实体并保存它(最好是批量保存)后,通过以下方式将它们重置为故障:

NSManagedObjectContext *moc = ...;
NSManagedObject *employee = ...;
[moc refreshObject:employee mergeChanges:NO];

通过在保存后调用 -refreshObject:mergeChanges:,它将从内存中删除该对象的属性和关系,并将其内存占用减少到接近零。您可以从那里将其存储在 NSDictionary 中以供以后进行关系映射。

这将避免所有的抓取并显着提高您的导入性能。

关于ios - 从 json 插入核心数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23523400/

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