sqlite ios : attempt to write a readonly database

前端 未结 5 1593
天涯浪人
天涯浪人 2021-01-15 05:52

I use a sqlite database for a project. I can do queries like SELECT but impossible to do INSERTs! On the simulator the INSERT works properly. As soon as I compile on my iPod

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-15 06:29

    All you need to do is change the root that you are saving your SQLite file in you phone which is readonly at the moment. make these changes :

    Add these codes to your AppDelegate :

    .h file:

    @property (nonatomic,retain) NSFileManager *fileMgr;
    @property (nonatomic,retain) NSString *homeDir;
    @property (nonatomic,retain) NSString *title;
    

    .m file:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [self checkAndCreateDatabase];
        return YES;
    }
    
    -(NSString *)GetDocumentDirectory{
        fileMgr = [NSFileManager defaultManager];
        homeDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        return homeDir;
    }
    
        -(void) checkAndCreateDatabase{
        BOOL success;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *databasePath = [self.GetDocumentDirectory stringByAppendingPathComponent:@"YOUR DATABASE NAME.sqlite"];
        success = [fileManager fileExistsAtPath:databasePath];
        if(success) {
            NSLog(@"working");
            return;}
        else{
            NSLog(@"notworking");
        NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"YOUR DATABASE NAME.sqlite"];
        [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
        }
    }
    

    Also in your SQLite class add these lines :

    .h file:

    @property (nonatomic,retain) NSFileManager *fileMgr;
    @property (nonatomic,retain) NSString *homeDir;
    

    .m file:

    -(NSString *)GetDocumentDirectory{
        fileMgr = [NSFileManager defaultManager];
        homeDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        return homeDir;
    }
    

    and also in INSERT and SELECT make these changes :

    NSString *dbPath = [self.GetDocumentDirectory stringByAppendingPathComponent:@"YOUR DATABASE NAME.sqlite"];
        const char *dbpath = [dbPath UTF8String];
    

    Hope it helps :)

提交回复
热议问题