2012-01-27 43 views
1

我的方法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

您是否登录过并检查过'... url absoluteString'是否正确 – 2012-01-27 10:07:20

回答

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的计数,您有一个填充的核心模型实体。

2

fileExistsAtPath:采取路径而不是URL?

NSString *file = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Mew.sqlite"]; 
BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:file]; 
+0

我更新了我的问题。 – Voloda2 2012-01-27 11:05:12

+0

我的答案依然如此。 fileExistsAtPath需要一个路径。你给它一个URL。 – 2012-01-27 11:07:56

相关问题