我在本書的幫助下學習Core Data。有一個代碼:專業核心數據手冊,示例代碼問題
- (void)loadData {
// Pull the movies. If we have 200, assume our db is set up.
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Movie"
inManagedObjectContext:context]];
NSArray *results = [context executeFetchRequest:request error:nil];
if ([results count] != 200) {
// Add 200 actors, movies, and studios
for (int i = 1; i <= 200; i++) {
[self insertObjectForName:@"Actor" withName:
[NSString stringWithFormat: @"Actor %d", i]];
[self insertObjectForName:@"Movie" withName:
[NSString stringWithFormat: @"Movie %d", i]];
[self insertObjectForName:@"Studio" withName:
[NSString stringWithFormat: @"Studio %d", i]];
}
// Relate all the actors and all the studios to all the movies
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Movie"
inManagedObjectContext:context]];
NSArray *results = [context executeFetchRequest:request error:nil];
for (NSManagedObject *movie in results) {
[request setEntity:[NSEntityDescription entityForName:@"Actor"
inManagedObjectContext:context]];
NSArray *actors = [context executeFetchRequest:request error:nil];
NSMutableSet *set = [movie mutableSetValueForKey:@"actors"];
[set addObjectsFromArray:actors];
[request setEntity:[NSEntityDescription entityForName:@"Studio"
inManagedObjectContext:context]];
NSArray *studios = [context executeFetchRequest:request error:nil];
set = [movie mutableSetValueForKey:@"studios"];
[set addObjectsFromArray:studios];
}
}
[request release];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
的主要問題是:是否有必要更新上下文指針,如果有在這方面的任何變化? 我的意思是:我在方法的開始處獲取指向上下文的指針,接下來在循環中,我接受此上下文並在那裏插入托管對象(-insertObjectForName:withName :)。然後我看到這個上下文指針的更新,並且有這樣一個問題:這是一種什麼規則,我應該採取相同的行動,還是僅僅不那麼簡潔的代碼示例?爲什麼我不能使用舊的指針?
---編輯---一個問題:是,這裏的請求的代碼的法律初始化:
兩個allocs只有一個版本?
然後,我應該重新創建請求和結果數組?或者他們會用舊指針來罰款? – Matubo
我剛剛從書籍網站下載了源代碼並刪除了這些行。它對應用程序沒有影響。這可能只是一個錯字。 –
也沒有勘誤發佈在那本書上... http://www.apress.com/9781430233558 –