Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

ios - NSCocoaErrorDomain Code=3840 issue while retrieving NSDATA to NSDictionary

I am creating iOS app which uses SQLite DB. I have created Table As:

const char *sql_stmt = "CREATE TABLE IF NOT EXISTS ORDERTABLE (ID INTEGER PRIMARY KEY AUTOINCREMENT, ITEMDESC BLOB)";

and then I have to insert self.selectedItemsDictnory Dictionary into ItemDESC i am inserting as :

NSData *data = [NSJSONSerialization dataWithJSONObject:self.selectedItemsDictnory options:NSJSONWritingPrettyPrinted error:nil];

NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO ORDERTABLE(ITEMDESC)VALUES( "%@");",data];

Upto this it is successfully done.

Now i have to retrieve this dictionary in same format

what i am doing is :

if (sqlite3_prepare_v2(orderDB, sqlStatement, -1, &statement, NULL) == SQLITE_OK) {

    while (sqlite3_step(statement) == SQLITE_ROW) {
        int uniqueId = sqlite3_column_int(statement, 0);

        const void *blob = sqlite3_column_blob(statement, 1);
        NSInteger bytes = sqlite3_column_bytes(statement, 1);
        NSData *data = [NSData dataWithBytes:blob length:bytes];
        NSError *error;

        NSMutableString *jsonObject=[NSJSONSerialization
                                         JSONObjectWithData:data
                                         options:NSJSONReadingMutableLeaves
                                         error:&error];
        NSLog(@"jsonObject is %@ with error %@",jsonObject, error);

    }

    sqlite3_finalize(statement);
    sqlite3_close(orderDB);
}

And I am getting Error as

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are not formatting the JSON property. In this:

NSData *data = [NSJSONSerialization dataWithJSONObject:self.selectedItemsDictnory options:NSJSONWritingPrettyPrinted error:nil];

Now you have a data blob, not a string, but below, you treat it as a string:

NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO ORDERTABLE(ITEMDESC)VALUES( "%@");",data];

If you want a string:

NSString *jsonString = [NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO ORDERTABLE(ITEMDESC)VALUES( "%@");",jsonString];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...