使用NSKeyedUnarchiver将NSData转换为NSDictionary时出错

时间:2013-03-22 10:57:59

标签: iphone ios objective-c nsdictionary nsdata

我想要archiveUnarchive包含NSDictionary个对象的数据。在Unarchiving数据时观察到崩溃。请在下面找到代码和错误,

归档:

 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:mydictobject];

解压:

 NSData *Objdata = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 2)   
                    length:sqlite3_column_bytes(statement, 2)];
 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] 
                                   initForReadingWithData:Objdata];
 NSDictionary *dict = [NSDictionary dictionaryWithDictionary:
                       [NSKeyedUnarchiver unarchiveObjectWithData:Objdata]];
[dict objectForKey:@"key1"];

错误:

*由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [NSKeyedUnarchiver initForReadingWithData:]:难以理解的存档(0xfffffff8,0xffffffc7,0xf, 0x1,0x2,0x0,0x0,0x0)' * *第一次抛出调用堆栈: (0x222b012 0x194e7e 0x222adeb 0xe78c90 0xe7f2 0x3c11 0x19256 0x43f8d5 0x43fb3d 0xe46e83 0x21ea376 0x21e9e06 0x21d1a82 0x21d0f44 0x21d0e1b 0x21857e3 0x2185668 0x39065c 0x2612 0x2545 0x1) libc ++ abi.dylib:terminate调用抛出异常

感谢。

1 个答案:

答案 0 :(得分:0)

// To read data do following
-(void) readAnimalsFromDatabase {

    // Setup the database object
    sqlite3 *database;

    // Init the animals Array
    dataArray = [[NSMutableArray alloc] init];

    // Open the database from the users filessytem
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        const char *sqlStatement = "select * from anyTable";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                NSString *aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

                NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:aName, @"name", aDescription, @"description", aImageUrl, @"imageURL", nil];

                // Add the animal object to the animals Array
                [dataArray addObject:dict];

            }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);

    }
    sqlite3_close(database);


    // Archive NSArray to NSData
    NSData *archiveData = [NSKeyedArchiver archivedDataWithRootObject:dataArray];

    // UnArchive NSData to NSDictionary
    NSArray *array = [NSArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:data]];
    NSLog(@"%@",array);
}