Search code examples
objective-csqlitefmdb

NSDocumentDirectory giving strange directory as output


I'm trying to open sqlite database from my documents directory:

NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dbFileName = [docDir stringByAppendingPathComponent:@"DatabaseName.sqlite"];

self.db = [FMDatabase databaseWithPath:dbFileName];

self.db.logsErrors = YES;

self.db = _db;
if ([self.db open]) {
    NSLog(@"database opened");

}
NSLog(@"docDir = %@",[NSString stringWithFormat:@"%@%@",docDir,dbFileName]);

NSLog shows strange path docDir = /Users/userName/Documents/Users/userName/Documents/DatabaseName.sqlite instead of /Users/userName/Documents/DatabaseName.sqlite. While opening there are no errors or warnings.

After this I tried get count(*) from my table

NSString *queryString = [NSString stringWithFormat:@"SELECT count(*) FROM histories"];
FMResultSet *result = [self.db executeQuery:queryString];
NSLog(@"count = %i", [result intForColumnIndex:0]);

Database has more when 10k rows but NSLog shows 0. Application is not for iOS, only Command Line. Where can I find the problem?


Solution

  • You have

    docDir = /Users/userName/Documents
    dbFileName = /Users/userName/Documents/DatabaseName.sqlite
    

    therefore in

    NSLog(@"docDir = %@",[NSString stringWithFormat:@"%@%@",docDir,dbFileName]);
    

    the docDir is printed twice (dbFileName already contains docDir).

    Remark: The statement self.db = _db; looks suspicious, you might want to remove that.

    Added: The FMDB documentation states:

    You must always invoke -[FMResultSet next] before attempting to access the values returned in a query, even if you're only expecting one.

    So your code probably should look like this:

    FMResultSet *result = [self.db executeQuery:queryString];
    if ([result next]) {
        NSLog(@"count = %i", [result intForColumnIndex:0]);
    }