gpt4 book ai didi

ios - 如何使用 NSMutableArray 的内容填充 Core Data/SQLite DB

转载 作者:行者123 更新时间:2023-11-29 01:29:17 25 4
gpt4 key购买 nike

我有一个名为 usersArrayNSMutableArray,我想将其填充到核心数据/SQLite 数据库/存储中。到目前为止,我已经构建了以下方法,但我认为它不会正确填充,我们将不胜感激任何帮助。

- (void)populateCDDB:(NSMutableArray *)usersArray {

NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:usersArray];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Account" inManagedObjectContext:_context]];

NSError *error = nil;
NSArray *objectsForImport = [_context executeFetchRequest:request error:&error];
NSArray *importKeys = [NSArray arrayWithObjects:@"username", @"pin", @"credit", @"email", @"lastLogin", @"rfid", @"phoneNumber", nil];

for (NSManagedObject *object in objectsForImport) {
// NSMutableArray *anObjectArray = [NSMutableArray arrayWithCapacity:[importKeys count]];
for (NSString *key in importKeys) {
id value = [object valueForKey:key];
if (!value) {
value = @"";
}
[usersArray addObject:[value description]];
}
}
//save the results to Core Data / SQLite store.
[_context save:&error];
}

是的,usersArray 是该类的一个实例变量。

最佳答案

好的,我理解评论的意思是您想要使用数组中的对象作为在核心数据中创建“帐户”对象的来源。

根据问题收集的数据,我假设数组中的对象和核心数据“帐户”实体都支持所有键。

由于您没有为数组中的对象指定类型或 API,我假设它们与您之前列出的名称的键值兼容,并且类型兼容。

- (BOOL)addUsersFromArray:(NSArray*)usersToAdd
intoMOC:(NSManagedObjectContext*)moc
error:(NSError**)error {
NSArray *importKeys = @[@"pin", @"credit", @"email", @"lastLogin", @"rfid", @"phoneNumber"];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Account"];
for (id user in usersToAdd) {
id username = [user valueForKey:@"username"];
// See if we already have an Account for this user - username is unique key
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"username = %@", username];
NSArray *fetched = [moc executeFetchRequest:fetchRequest error:error];
if (fetched == nil) return NO;

NSManagedObject *account = [fetched firstObject];
if (account == nil) {
account = [NSEntityDescription insertNewObjectForEntityForName:@"Account" inManagedObjectContext:moc];
[account setValue:username forKey:@"username"];
}
for (NSString *key in importKeys) {
id value = [user valueForKey:key];
if (value) {
[account setValue:value forKey:key];
}
}

}
return YES;
}

关于ios - 如何使用 NSMutableArray 的内容填充 Core Data/SQLite DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621273/

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