如何从iOS中的sqlite DB中检索和存储NSArray

时间:2013-05-03 08:59:25

标签: ios sqlite nsarray nskeyedarchiver

我有一个数组itemQtyArray,我将其存储在SQLITE表中:

    NSData *toData = [NSKeyedArchiver archivedDataWithRootObject:self.itemQtyArray];

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

然后我将检索为:

    const void *itemQty = sqlite3_column_text(statement, 2);
    NSInteger qtyBytes = sqlite3_column_bytes(statement, 2);
    NSData *data2 = [NSData dataWithBytes:itemQty length:qtyBytes];
    NSArray *myArrayFromDB = [[NSArray alloc]init];
    myArrayFromDB = [NSKeyedUnarchiver unarchiveObjectWithData:data2];
    [self.itemQtyArray addObjectsFromArray:myArrayFromDB];

BUt我在第

行获得了Exception
    myArrayFromDB = [NSKeyedUnarchiver unarchiveObjectWithData:data2];

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因是:

    '-[__NSCFData objectForKey:]: unrecognized selector sent to instance

请告诉我有什么问题

1 个答案:

答案 0 :(得分:3)

NSData *toData = [NSKeyedArchiver archivedDataWithRootObject:array];

而不是你应该传递NSDictionary

NSData *toData = [NSKeyedArchiver archivedDataWithRootObject:dictionary];

o将通用数组转换为NSData,需要一个归档器!如果您知道如何提供NSData,您就知道如何使用NSKeyedArchiver。所以:

NSArray* array= ... ;
NSData* data=[NSKeyedArchiver archivedDataWithRootObject:array];

当然,阵列中的所有元素都需要实现NSCoding协议