2011-03-07 22 views
2

調用的方法在另一類我走到這一步......這是我的代碼:的Objective-C:需要從FinishedLaunching

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

現在的問題是:這段代碼是應該檢查查看數據庫是否存在,如果不存在,創建它。我的問題是我有一個問題搞清楚究竟如何寫入被調用的方法的第一行,以及它在SQLiteDB.m中的位置。這是一個實例方法( - )還是一個類方法(+)?

對不起,我對此感到慚愧,但是一旦我看到它,我就會喋喋不休......其餘的代碼是用C#編寫的,我可以處理轉換爲Obj_C 。

回答

0

以下是將現有數據庫從Bundle複製到Documents目錄的方法,但可以輕鬆地對新數據庫進行調整。只需使用下面的fileExistsAtPath:方法邏輯,並用您的自定義數據庫創建代碼替換要執行的操作。

在AppDelegate.m文件將這個:

- (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); 
     } 
    } 
} 
applicationDidFinishLaunching:方法調用

那麼這個:

[self prepareDatabase]; 
+0

theChrisKent:這就是我正在尋找的信息。 。 非常感謝!並感謝那些回覆的人。 – SpokaneDude 2011-03-07 20:38:56

0

我假設通過「看看數據庫是否存在」,你的意思是「看看數據庫文件是否存在於磁盤上」。爲此,您使用NSFileManager類的方法fileExistsAtPath:。這是一種實例方法,但您可以使用[NSFileManager defaultIntance]

首先計算文件的路徑(這取決於你如何)。檢查文件是否存在。如果是,請打開該文件,如果沒有,則使用該文件名創建一個新的數據庫。

+0

在iOS系統和Mac OS x垂直10.5及更高版本,你應該考慮使用[ NSFileManager alloc] init]而不是singleton方法defaultManager。 NSFileManager的實例在使用[[NSFileManager alloc] init]創建時被認爲是線程安全的。 – 2011-03-07 20:30:18

+0

即使是線程安全的文件管理器也不會從「檢查/如果未找到,創建」場景中的競態條件中進行保存。 – 2011-03-07 20:32:32

+0

謝謝..我已經有了邏輯,但仍然不知道該方法是什麼樣的......我想從上面的代碼中調用方法(不知道它是實例還是類方法)。我認爲我的調用是正確的,但不知道目標代碼是什麼樣的(我只需要第一行,即 - (id)initSQLiteDB ...) – SpokaneDude 2011-03-07 20:32:38