2012-12-19 28 views
1

我正在做一個小型的數據庫驅動的應用程序。我有我的SQLite db文件在支持文件 xcode。起初,我試圖在主包中寫入數據,但不能。搜索後,我遇到了this答案,並將我的代碼更改爲以下內容。Cocoa錯誤:516同時使SQLite數據庫的可寫副本

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

     BOOL success; 
     NSFileManager *filemngr = [[NSFileManager alloc] init]; 
     NSError *error; 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); 
     NSString *documentDirectory = [paths objectAtIndex:0]; 
     NSString *writableDbPath = [documentDirectory stringByAppendingPathComponent:@"contacts.sqlite"]; 
     success = [filemngr fileExistsAtPath:writableDbPath]; 
     if(!success) 
     { 
      [status setText:@"Error occurred!"]; 
     } 

     NSString *defaultDbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"contacts.sqlite"]; 
     success = [filemngr copyItemAtPath:defaultDbPath toPath:writableDbPath error:&error]; 
     if (!success) 
     { 
      [status setText:[error localizedDescription]]; 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" 
                  message:[error localizedDescription] 
                  delegate:nil 
                cancelButtonTitle:@"OK" 
                otherButtonTitles:nil]; 
      [alert show]; 
     } 
    } 

我得到以下錯誤在最後,如果當我試圖將文件複製到可寫位置(其中UIAlertView中所示)塊。

操作無法完成。 (可可錯誤516)

任何人都可以請告訴我如何糾正這個錯誤?

謝謝。

回答

3

如果文件尚未複製到文件目錄,您希望將該文件複製到文件目錄。 在你的代碼中,如果文件已經存在,那麼你也試圖將它複製到文檔目錄中。這將導致執行第二個if(!success)塊。 改變你的方法,如:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

     BOOL success; 
     NSFileManager *filemngr = [[NSFileManager alloc] init]; 
     NSError *error; 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); 
     NSString *documentDirectory = [paths objectAtIndex:0]; 
     NSString *writableDbPath = [documentDirectory stringByAppendingPathComponent:@"contacts.sqlite"]; 
     success = [filemngr fileExistsAtPath:writableDbPath]; 
     if(!success) 
     { 
      NSString *defaultDbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"contacts.sqlite"]; 
     success = [filemngr copyItemAtPath:defaultDbPath toPath:writableDbPath error:&error]; 
      if (!success) 
      { 
      [status setText:[error localizedDescription]]; 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" 
                  message:[error localizedDescription] 
                  delegate:nil 
                cancelButtonTitle:@"OK" 
                otherButtonTitles:nil]; 
      [alert show]; 
      } 
     } 
    } 
+0

非常感謝你的Midhun。這個錯誤消失了,但我還有一個小問題。現在在我的.h文件中,我有一個像這樣的'NSString * databasePath'的數據庫路徑的引用。在我將數據保存到數據庫的.m文件中,我像這樣檢索該值。 'const chat * dbpath = [databasePath UTF8String]'。我必須將新的'writableDbPath'值賦給那個嗎?因爲我的保存數據現在不起作用。我在'viewDidLoad'方法中嘗試了'databasePath = writableDbPath',但沒有奏效。我該怎麼辦?再次感謝:) – Isuru

+0

@Isuru:高興:) –

+0

@Isuru:你的databasePath應該是文檔目錄中的路徑。您在使用時需要指定路徑 –

相關問題