Voloda2
Voloda2

Reputation: 12607

Core Data: I want to populate my database only for a first run

My method checkIfExistDatabase must returns YES for a second run, but it returns NO. That's a problem.

- (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: I added applicationDocumentsDirectory method

- (NSURL *)applicationDocumentsDirectory
{
  return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

and output:

NSLog(@"absolute string: %@", [url absoluteString]);

absolute string: file://localhost/var/mobile/Applications/6EE4D791-B798-4A2E-83DD-BFA41ED86940/Documents/Mew.sqlite

Upvotes: 1

Views: 345

Answers (2)

LJ Wilson
LJ Wilson

Reputation: 14427

Don't check for existence of the entity, check for objects (records) in that entity. Something like this:

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];

If you have a count greater than 0, you have a populated core model entity.

Upvotes: 2

Stephen Darlington
Stephen Darlington

Reputation: 52565

Doesn't fileExistsAtPath: take a path rather than a URL?

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

Upvotes: 2

Related Questions