iOSAppDev
iOSAppDev

Reputation: 2783

Database file is not copied in documents directory

When I run my application , I cant perform DB operations. When I check documents directory of iphone simulator it doesn't contain db file. Here is my code

-(id)init
{
    [super init];

    databaseName=@"DSMDatabase.sqlite";

    NSArray * documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString * documentDir=[documentsPaths objectAtIndex:0];

    databasePath=[documentDir stringByAppendingPathComponent:databaseName];

    return self;
}

-(void)checkAndCopyDB
{
    BOOL success;

    NSFileManager * fileManager=[NSFileManager defaultManager];

    success=[fileManager fileExistsAtPath:databasePath];

    if(success) return;

    NSString * databasepathfromapp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    [fileManager copyItemAtPath:databasepathfromapp toPath:databasePath error:nil];

    [fileManager release];

}

Upvotes: 0

Views: 244

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

In -init you're assigning an autoreleased value to databasePath. Depending on how -checkAndCopyDB is called, there's an excellent chance that databasePath has already been deallocated and that the variable is now pointing to something completely different.

You could deal with this by retaining databasePath in init but really there's no reason to keep this in a separate method. I'd move the databasePath-related code in init down into checkAndCopyDB, which would work just as well and avoid autorelease issues.

Upvotes: 1

Related Questions