我的方法checkIfExistDatabase必须为第二次运行返回YES,但它返回NO。那是个问题。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[CoreDataWrapper sharedInstance] checkIfExistDatabase];
return YES;
}
-(void) checkIfExistDatabase
{
NSURL *url = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Mew.sqlite"];
BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:[url absoluteString]];
if (!isExists)
{
[self populateDatabase];
}
}
-(void) populateDatabase
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Test" inManagedObjectContext:[self managedObjectContext]];
for (int i =0; i<2; i++)
{
Test *test = [[[Test alloc] initWithEntity:entity insertIntoManagedObjectContext:[self managedObjectContext]] autorelease];
test.text = @"Text";
test.index = [NSNumber numberWithInt:i];
}
[self saveContext];
}
更新:我添加了applicationDocumentsDirectory方法
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
并输出:
NSLog(@"absolute string: %@", [url absoluteString]);
absolute string: file://localhost/var/mobile/Applications/6EE4D791-B798-4A2E-83DD-BFA41ED86940/Documents/Mew.sqlite
答案 0 :(得分:2)
fileExistsAtPath:
不是路径而不是网址?
NSString *file = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Mew.sqlite"];
BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:file];
答案 1 :(得分:2)
不检查实体是否存在,检查该实体中的对象(记录)。像这样:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Test" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSError *error = nil;
NSUInteger count = [self.managedObjectContext countForFetchRequest:request error:&error];
如果计数大于0,则表示您拥有一个已填充的核心模型实体。