以下是在sqlite db中获取数据的代码:
-(id) init {
if ((self = [super init])) {
NSString *sqLiteDb = [[NSBundle mainBundle]pathForResource:@"CourseFindr" ofType:@"sqlite"];
if (sqlite3_open([sqLiteDb UTF8String], &_db) != SQLITE_OK){
NSLog(@"Failed to open database!");
}
}
return self;
}
-(void)dealloc {
sqlite3_close(_db);
}
- (NSArray *)job {
NSMutableArray *retrieve = [[NSMutableArray alloc] init];
NSString *query = @"SELECT jID, jName, jDesc, jEarnings, jTags FROM jobs";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_db, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
int _jID = sqlite3_column_int(statement, 0);
char *jNameChars = (char *) sqlite3_column_text(statement,1);
char *jDescChars = (char *) sqlite3_column_text(statement, 2);
char *jEarningsChars = (char *) sqlite3_column_text (statement, 3);
char *jTagsChars = (char *) sqlite3_column_text(statement, 4);
NSString *_jName =[[NSString alloc]initWithUTF8String:jNameChars];
NSString *_jDesc = [[NSString alloc]initWithUTF8String:jDescChars];
NSString *_jEarnings = [[NSString alloc]initWithUTF8String:jEarningsChars];
NSString *_jTags = [[NSString alloc]initWithUTF8String:jTagsChars];
Jobs *jobs = [[Jobs alloc]
initWithJID:_jID
jName:_jName
jDesc:_jDesc
jEarnings:_jEarnings
jTags:_jTags];
[retrieve addObject:jobs];
}
sqlite3_finalize(statement);
}
return retrieve;
}
但它一直在崩溃:
2014-01-09 21:12:39.565 CourseFindr[4595:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSPlaceholderString initWithUTF8String:]: NULL cString'
*** First throw call stack:
(
0 CoreFoundation 0x018255e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x015a88b6 objc_exception_throw + 44
2 CoreFoundation 0x018253bb +[NSException raise:format:] + 139
3 Foundation 0x0120fb49 -[NSString initWithUTF8String:] + 89
4 CourseFindr 0x000036b5 -[CourseFindrDB jobs] + 645
5 libdyld.dylib 0x01e61725 start + 0
6 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
我不确定这是因为我的libsqlite3.dylib还是与我的数据库不兼容? 我的数据库名为'CourseFindr.sqlite'表是
JOBS Table
-jID PK
-jName
-jDesc
-jEarnings
-jTags
它还会在崩溃时保持重定向到main.m.
我以前做过这个,但没有错误。这次我在没有教程的情况下尝试它,但似乎我错过了一些东西。 :/
答案 0 :(得分:2)
崩溃日志:
2014-01-09 21:12:39.565 CourseFindr [4595:a0b] *由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'* - [NSPlaceholderString initWithUTF8String:]:NULL cString “
告诉您正在向initWithUTF8String
传递NULL指针。这是崩溃的原因,并且是根据Apple docs预期的行为:
initWithUTF8String:
...
重要说明:如果bytes为NULL,则引发异常。
因此,检查您传递给initWithUTF8String
方法的内容并添加防范以防止传递NULL。类似的东西:
char *jNameChars = (char *) sqlite3_column_text(statement,1);
...
NSString *_jName = jNameChars?[[NSString alloc]initWithUTF8String:jNameChars]:@"";
答案 1 :(得分:0)
您可以在异常的第一行找到解决方案。
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSPlaceholderString initWithUTF8String:]: NULL cString'
这意味着您将空字符串传递给initWithUTF8String方法。
答案 2 :(得分:0)
NSLog您传递的所有字符串。因为您将空值传递给initWithUTF8String