开发者

Objective-C: need to call a method in another class from FinishedLaunching

I got this far... here is my code:

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    //  create the d/b or get the connection value
    SQLiteDB *dbInstance = [[SQLiteDB alloc] init];
}

Now, the question is: this bit of code is supposed to check to see if a database exists, and if not, create it. My problem is I am having a problem figuring out exactly how to write the first line of the called method and where to place it in SQLiteDB.m. Is this an instance method (-) or开发者_如何转开发 a class method (+)?

I'm sorry for being so lame on this, but once I see it, I'll have the hang of it... the rest of the code is written in C#, and I can handle the conversion to Obj_C.


The following is a method to copy an existing database from your Bundle to the Documents directory, but can easily be adapted for a new database. Just use the fileExistsAtPath: method logic below and replace the actions to take with your custom database creation code.

Put this in your AppDelegate.m file:

- (void)prepareDatabase
{
    //add Database Versioning check to see if the resources database is newer
    // generally as simple as naming your database with a version on the end

    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSString *databasePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:@"/YOURDATABASE.s3db"];
    if(![filemanager fileExistsAtPath:databasePath]) {
        //Database doesn't exist yet, so we copy it from our resources
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/YOURDATABASE.s3db"];
        if([filemanager copyItemAtPath:defaultDBPath toPath:databasePath error:nil]) {
            NSLog(@"Database Copied from resources");           
        } else {
            NSLog(@"Database copy FAILED from %@ to %@",defaultDBPath,databasePath);
        }
    }
}

Then in your applicationDidFinishLaunching: method call this:

[self prepareDatabase];


I'm assuming that by "see if the database exists" you mean "see if the database file exists on disk". For that, you use method fileExistsAtPath: of class NSFileManager. It's an instance method, but you can use [NSFileManager defaultIntance].

Calculate the path to the file first (it's up to you how). Check if the file exists. If yes, open the file, if not, create a new database with that filename.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜