I’m an Objective-C newbie and I’m studying iPhone programming.
In my appDelegate, in the -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method, I’ve a class member (@syntethized) called databasePath.
I set its value this way:
databasePath = [self copyDatabaseToDocuments];
I copied the entire copyDatabaseToDocuments method from a wonderful book by Alasdair Allan and made very little changes (the name of the db is the only thing I changed):
-(NSString *)copyDatabaseToDocuments{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath=[paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"myDb.sqlite"];
//
if(![fileManager fileExistsAtPath:filePath]){
NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myDb.sqlite"];
[fileManager copyItemAtPath:bundlePath toPath:filePath error:nil];
}
return filePath;
}
I NSLog the databasePath and I regularly get its value (it is a string path and it is not null) after the assignment.
Then, I have a method -(NSMutableArray*)readDatabase:(char*)querySQL I call from a ViewController through a delegate reference.
Anything works fine if -inside this last method- I assign again the value of databasePath.
But, if I don’t assign it again AND I want to use its value (that I suppose it was set in the -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method) the app crashes.
Why?
Make sure that your @property for databasePath looks like this:
And then set it in this way:
It is probably crashing because copyDatabaseToDocuments returns an autoreleased string, and unless you use the self. notation to set databasePath, that autoreleased string can go away at any time.