是否可以将数据从 .plist 加载到核心数据对象?
我有这个代码:
NSURL *url = [[NSBundle mainBundle] URLForResource"List" withExtension"plist"];
NSDictionary *plistContent = [NSDictionary dictionaryWithContentsOfURL:url];
NSArray *name = [plistContent objectForKey"Name"];
NSArray *surname = [plistContent objectForKey"Surname"];
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
for (NSString *aName in name) {
for (int i = 0; i < name.count; i++) {
[newManagedObject setValue:nameSt forKey"name"];
}
}
for (NSString *aSurname in content) {
for (int i = 0; i < content.count; i++) {
[newManagedObject setValue:contentSt forKey"surname"];
}
}
[self saveContext];
我有 3 个带名字的字符串和 3 个带姓氏的字符串,但是在
newManagedObject 仅从每个数组中加载 1 个字符串。请帮我解决这个问题
Best Answer-推荐答案 strong>
您只创建一个对象,但您应该创建 3 个(在循环内)。你也应该只有 1 个循环(不是你目前拥有的 4 个......):
NSURL *url = [[NSBundle mainBundle] URLForResource"List" withExtension"plist"];
NSDictionary *plistContent = [NSDictionary dictionaryWithContentsOfURL:url];
NSArray *names = [plistContent objectForKey"Name"];
NSArray *surnames = [plistContent objectForKey"Surname"];
if (names.count == surnames.count) {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
for (int i = 0; i < names.count; i++) {
NSString *name = names[i];
NSString *surname = surnames[i];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:name forKey:@"name"];
[newManagedObject setValue:surname forKey:@"surname"];
}
[self saveContext];
} else {
// error...
}
关于ios - 将数据从 NSArray 加载到 NSManagedObject,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/28914323/
|