将数据(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");
}
}
Run Code Online (Sandbox Code Playgroud)
保存上面的工作正常,我在保存到上下文之前非常仔细地调试了所有数据,以确保没有任何属性NULL.
问题始终在于songWebLink属性,有时当我尝试将其返回到下面时它会变为null:
- (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
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我NSLog的songWebLink,它得到NULL,一旦第4次迭代,然后6日,然后第二等,这是随机读取时分配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;
}
Run Code Online (Sandbox Code Playgroud)
获取MOC对象以在其他类中使用它:
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
context = [appDelegate managedObjectContext];
Run Code Online (Sandbox Code Playgroud)
示例项目: 如果您认为需要查看应用程序项目,我制作了一个简化版本,我在其上复制了该错误,您可以在此处下载.
| 归档时间: |
|
| 查看次数: |
733 次 |
| 最近记录: |