본문 바로가기

iPhone

Device에서 Sqlite 사용

단순히 Read(select문)을 사용할 경우 main bundle에서 사용해도 되지만,
그외에 write(insert, update, delete문)을 사용할 경우, 권한 문제로
sqlite파일을 Document폴더에 복사 후 사용해야 한다.

아래는 복사 코드. 

 NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];    
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"DB이름.sqlite"];

    

    BOOL dbexits = [fileManager fileExistsAtPath:writableDBPath];
    if (!dbexits) 
    {
        // 데이터베이스가 존재하지 않으면, 어플리케이션 Resource아래에서 복사를 한다
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DB이름.sqlite"];
        NSError *error;
        BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];


        if (!success) 
        {
            NSAssert1(0, @"Failed to create writable database file with message '%@'.",
                      [error localizedDescription]);
        }
    }