我将数据库值转换为JSON格式。它在URL中显示为JSON。然后我从JSON URL获取值,然后存储到本地数据库。但我收到以下错误:[__NSCFString objectForKey:]: unrecognized selector sent to instance 0xa6a2750
和*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0xa6a2750'
网址中的JSON值:
[{"cat_id":"196","category_name":"Performance Parts"},{"cat_id":"212","category_name":"Car Care"}]
获取价值并插入本地:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Mdb.sqlite"];
NSLog(@"filepath %@",path);
//NSDictionary *jsonDict = [stringFromFileAtURL JSONValue];
//array
NSArray *userData = [str JSONValue];
// NSLog(@"userData is %@", userData);
BOOL notExist = TRUE;
sqlite3_stmt *statement, *addStmt;
for (NSArray *skarray in userData) {
NSLog(@"test");
for (NSDictionary *tuser in skarray) {
NSLog(@"test1");
//write all this in the table
//if already exists in data base id then overwrite the name
//category table
//NSLog(@"CategoryId is %@",[tuser objectForKey:@"cat_id"]);
//NSLog(@"CategoryName is %@",[tuser objectForKey:@"cat_name"]);
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
NSLog(@"test2");
const char *sql = [[NSString stringWithFormat:@"SELECT cat_id FROM categories where cat_id = '%@'",[tuser objectForKey:@"cat_id"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(@"test3");
NSLog(@"check category is %s", sql);
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
notExist = TRUE;
while (sqlite3_step(statement) == SQLITE_ROW) {
notExist = FALSE;
}
}
if(notExist){
//NSLog(@"cat id does not exist");
const char *sqlInsert = [[NSString stringWithFormat:@"insert into categories (cat_id, category_name) values ('%@', '%@')", [tuser objectForKey:@"cat_id"], [tuser objectForKey:@"category_name"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Insert category is %s", sqlInsert);
if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
}
}
答案 0 :(得分:1)
删除for (NSArray *skarray in userData) {
循环并使用
for (NSDictionary *tuser in userData) {
NSLog(@"test1");
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
const char *sql = [[NSString stringWithFormat:@"SELECT cat_id FROM categories where cat_id = '%@'",[tuser objectForKey:@"cat_id"]] cStringUsingEncoding:NSUTF8StringEncoding];
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
notExist = TRUE;
while (sqlite3_step(statement) == SQLITE_ROW) {
notExist = FALSE;
}
}
答案 1 :(得分:0)
您尝试从NSDictionary
(或可变)获取数据,但在您的情况下,它会以某种方式转换为NSString
(NSCFString
)且没有{{1属性。在使用objectForKey
的地方查看您正在编译的步骤。