0
我在plist中有一組項目。當我的應用程序啓動時,我的plist中讀取並保存爲一個數組在我的DataManager單身,就像這樣:使用數據管理器單例管理核心數據對象
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *itemDatapath = [path stringByAppendingPathComponent:@"ItemData.plist"];
NSDictionary *itemData = [NSDictionary dictionaryWithContentsOfFile:itemDatapath];
dataManager.items = [itemData objectForKey:@"Items"];
我也想存儲與此數據在DataManger相關的核心數據對象,所以我嘗試這樣的:
-(void)setItems:(NSArray *)_items //causes EXC_BAD_ACCESS error
{
self.items = _items;
NSManagedObjectContext *context = [self managedObjectContext];
for (NSDictionary *item in self.items)
{
NSManagedObject *itemObject = [NSEntityDescription
insertNewObjectForEntityForName:@"Item"
inManagedObjectContext:context];
[itemObject setValue:[NSNumber numberWithInteger:[[item valueForKey:@"id"] intValue]] forKey:@"identifier"];
[itemObject setValue:[UIImage imageNamed:[item valueForKey:@"image"]] forKey:@"image"];
...
}
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
是,在我的應用程序的任何地方,我可以從這種方法訪問對象的點:
-(NSArray*)fetchItems
{
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Item" inManagedObjectContext:managedObjectContext];
NSError *error2;
NSFetchRequest *itemFetchRequest = [[NSFetchRequest alloc] init];
[itemFetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"order"
ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[itemFetchRequest setSortDescriptors:sortDescriptors];
NSArray *fetchedItems = [managedObjectContext executeFetchRequest:itemFetchRequest error:&error2];
return fetchedItems;
}
的問題是EXC_BAD_ACCESS錯誤記d以上。我還想知道是否有更好的方法來解決這個問題。我覺得在這裏存儲核心數據對象並不是最佳實踐。但是,即使我在其他視圖控制器中需要數據時獲取數據,如果更改核心數據對象,我如何管理它們?我有一個可能會改變的外部plist,並且核心數據對象需要基於此更新。