Why does an 'NSInvalidArgumentException' occur in this code?

1

I have a class that manages my entire database, my project is in Swift but I have two classes in Objective-C to bridge the classes and my Helper .

p>

After some testing on the iOS simulator I had the following error message:

  

Terminating app due to uncaught exception   'NSInvalidArgumentException', reason: '*** + [NSString   stringWithUTF8String:]: NULL cString '

Why did this happen?

Follow my two classes:

SQLiteObjc.h :

#import <Foundation/Foundation.h>
#import "sqlite3.h"

@interface SQLiteObjc : NSObject

+ (void) bindText:(sqlite3_stmt *)stmt idx:(int)idx withString: (NSString*)s;

+ (NSString*) getText:(sqlite3_stmt *)stmt idx:(int)idx;

@end

SQLiteObjc.m :

#import "SQLiteObjc.h"

@implementation SQLiteObjc

+ (void) bindText:(sqlite3_stmt *)stmt idx:(int)idx withString: (NSString*)s {
    sqlite3_bind_text(stmt, idx, [s UTF8String], -1, nil);
}

+ (NSString*) getText:(sqlite3_stmt *)stmt idx:(int)idx {
    char *s = (char *) sqlite3_column_text(stmt, idx);
    NSString *string = [NSString stringWithUTF8String:s];
    return string;
}

@end
    
asked by anonymous 24.06.2015 / 19:32

2 answers

1

You are trying to initialize a string with a null value in the following line:

NSString *string = [NSString stringWithUTF8String:s];

So you should test if you have a valid c string before trying to build an NSString. Aldo type:

+ (NSString*) getText:(sqlite3_stmt *)stmt idx:(int)idx {
    char *s = (char *) sqlite3_column_text(stmt, idx);
    if (s != NULL)
        return [NSString stringWithUTF8String:s];
    return nil;
}
    
24.06.2015 / 20:32
0

Test if "s"! = NULL is the same thing as just testing "s".

So:

+ (NSString*) getText:(sqlite3_stmt *)stmt idx:(int)idx {
char *s = (char *) sqlite3_column_text(stmt, idx);
if (s)
    return [NSString stringWithUTF8String:s];
return nil;

}

The code gets cleaner. You see, both ways are correct. The second is just an implicit way of testing the same thing. Ah! It also works if you need to deny the condition:

if(!s)...
    
20.07.2015 / 20:29