Why is there a 'Nsinvalidargumentexception' in this code?

Asked

Viewed 83 times

1

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

After some testing in iOS simulator I got the following error message:

Terminating app due to uncaught Exception 'Nsinvalidargumentexception', Reason: '***+[Nsstring stringWithUTF8String:]: NULL cString'

Why did this occur?

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

2 answers

1


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

NSString *string = [NSString stringWithUTF8String:s];

Therefore, you should test if you have a valid c string before trying to build a Nsstring. Aldo of 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;
}

0

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

Thus:

+ (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)...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.