我的方法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];
}
UPDATE:我添加了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
不要检查实体的存在,检查该实体中的对象(记录)。类似这样的东西:
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,则表示已填充核心模型实体。
fileExistsAtPath:
不是采用路径而不是URL吗?
NSString *file = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Mew.sqlite"];
BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:file];