データ (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
属性にあり、下に戻そうとすると 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
}
}
問題は、私が NULL を取得NSLog
するsongWebLink
と、4 回目の反復で 1 回、次に 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];
サンプル プロジェクト:アプリ プロジェクトを確認する必要がある場合は、バグを再現した簡略版を作成しました。ここから ダウンロードできます。