插入Core Data
突然停止工作。persistentStoreCoordinator
我使用以下代码设置我的。请注意,url
是Spot.sqlite
.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Spot.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
我运行应用程序,然后执行
cd ~/Library/Application Support/iPhone Simulator/7.0/Applications
find . -name MyAppName
A1DF7916-AE39-4367-BFD2-22A8BAA2AFD2
cd A1DF7916-AE39-4367-BFD2-22A8BAA2AFD2/Documents
ls
(results) Spot.sqlite Spot.sqlite-shm Spot.sqlite-wal
sqlite3 Spot.sqlite
sqlite> .tables
ZMYCATEGORY Z_METADATA Z_PRIMARYKEY
sqlite> select * from ZMYCATEGORY;
并且没有显示任何结果,但是当我选择Z_METADATA
.
这是我用来在托管对象上下文中插入对象的代码:
+ (void)insertParentCategoriesIntoCoreDataFromArray:(NSArray *)array {
ROAppDelegate *delegate = (ROAppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *managedObjectContext = [delegate managedObjectContext];
NSEntityDescription *categoryEntity = [NSEntityDescription entityForName:@"ROCategory" inManagedObjectContext:managedObjectContext];
for (int i = 0; i < [array count]; i++) {
ROCategory *category = [[ROCategory alloc] initWithEntity:categoryEntity insertIntoManagedObjectContext:managedObjectContext];
NSArray *mySQLRow = [array objectAtIndex:i];
NSString *name = [mySQLRow objectAtIndex:1];
[category setValue:name forKey:@"name"];
}
}
当我单步执行此代码时,它会按预期执行。不会发生错误。然而相关的 sqlite 表仍然是空的,当我运行以下代码时,我得到一个空的结果集。
...
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name ==[c] \'%@\'", key]]; // the [c] means case-sensitive
[request setEntity:categoryEntity];
NSError *error;
fetchedObjects = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];