将数据(10 条记录)保存到实体后,我正在处理获取请求以再次获取所有数据:
//Saving data
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//Save to coredata
song = [NSEntityDescription insertNewObjectForEntityForName:@"Song"
inManagedObjectContext:context];
[song setValue:title forKey:@"title"];
[song setValue:songLink forKey:@"songWebLink"];
NSLog(@"Song link : %@",songLink);//Never get NULL
[song setValue:albumLink forKey:@"albumImageLink"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}else{
NSLog(@"Record saved correctly");
}
}
上面的保存工作正常,我在保存到上下文之前非常仔细地调试了所有数据,以确保没有任何属性是NULL
.
问题始终出在songWebLink
属性上,有时当我尝试将其返回到下面时它会变为空:
- (void)parserDidEndDocument:(NSXMLParser *)parser{
NSEntityDescription *songEntity=[NSEntityDescription entityForName:@"Song" inManagedObjectContext:context];
NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
[fetch setEntity:songEntity];
NSError *fetchError;
NSArray *fetchedSongs=[context executeFetchRequest:fetch error:&fetchError];
NSMutableArray *songs = [[NSMutableArray alloc] init];
for (NSManagedObject *songObject in fetchedSongs) {
//here is the issue: this for loop will go through 10 iterations, songWebLink is randomly NULL, sometimes it's the fourth iteration, sometimes the 8th, sometimes the 5th.
NSLog(@"song web link: %@",[songObject valueForKey:@"songWebLink"]);//albumImageLink and title attributes are fine
}
}
问题是,当 I 时NSLog
,songWebLink
它得到 NULL,第 4 次迭代一次,然后是第 6 次,然后是第 2 次等等。它在获取时将 NULL 随机分配给属性。保存数据时,我确保NULL
. songWebLink
所以我打赌别的东西是这个问题的原因。
有什么想法吗?
编辑
以下是 MOC 的初始化方式:
AppDelegate.m:
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];//I tried initWithConcurrencyType:NSMainQueueConcurrencyType
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
让 MOC 对象在不同的类中使用它:
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
context = [appDelegate managedObjectContext];
示例项目: 如果您认为需要查看应用程序项目,我制作了一个简化版本,并在上面复制了错误,您可以在这里下载。