1

我正在做一个小型数据库驱动的应用程序。我在 xcode的Supporting Files下有我的 SQLite db 文件。起初,当它在主包中时,我试图向它写入数据,但不能。搜索后,我遇到了这个答案,我将代码更改为以下内容。

- (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 的位置)时,我在最后的 if 块中收到以下错误。

操作无法完成。(可可错误 516)

谁能告诉我如何纠正这个错误?

谢谢你。

4

1 回答 1

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];
          }
        }
    }
于 2012-12-19T10:58:45.273 回答