如何在NSmutablearray中解码对象

时间:2011-03-17 19:07:02

标签: iphone objective-c sqlite

我正在创建一个SQLite数据库。

要从表中获取数据,我在appdelegate.m类中使用此代码:

-(void) readItemsFromDatabaseforTable:(NSString *)tableName {
    // Setup the database object
    sqlite3 *database;

    // Init the animals Array
    itemsList = [[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
        NSString *sql_str = [NSString stringWithFormat:@"select * from %@", tableName];

        const char *sqlStatement = (char *)[sql_str UTF8String];
        NSLog(@"query %s",sqlStatement);
        //const char *sqlStatement = "select * from allcategories" ;
        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)];
                NSInteger aDescription =(compiledStatement, 2);
                //  NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

                // Create a new animal object with the data from the database

                Category *item = [[Category alloc] initWithName:aName Quantity:aDescription];

                // Add the animal object to the animals Array
                [itemsList addObject:item];

                [item release];
            }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);

    }
    sqlite3_close(database);

}

我在viewcontroller.m类中获取此数组,如下所示:

MyGroceryListAppDelegate *appDelegate = (MyGroceryListAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"%@",appDelegate.itemsList);

它显示如下输出:

(
    "<Category: 0x6b355d0>",
    "<Category: 0x6b356e0>",
    "<Category: 0x6b35790>",
    "<Category: 0x6b35830>",
    "<Category: 0x6b358d0>",
    "<Category: 0x6b35980>",
)

如何将此转换为普通数组?

1 个答案:

答案 0 :(得分:2)

如果您可以发布Category对象的标题,它将为我们提供更多信息。但你可能想在它上面实现描述方法。

-(NSString *)description{
    return [NSString stringWithFormat:@"Name:%@ Quantity:%i",self.name,self.quantity];
}