2011-03-17 54 views
0

我正在创建一个SQLite数据库。如何在NSmutablearray中解码对象

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>", 
) 

如何将此转换为正常数组?

+0

是否有任何理由使用sqlite而不是核心数据?这很少是正确的选择(没什么可说的,在这种情况下是错误的选择)。 – MCannon 2011-03-17 19:10:04

+0

是的,我需要使用sqlite。 – MaheshBabu 2011-03-17 19:11:18

+0

我只是好奇你的理由是什么。它是远程数据库还是个人偏好?无论如何,希望我的回答有帮助 – MCannon 2011-03-17 19:20:51

回答

2

如果你可以发布Category对象的头部,它会给我们更多的继续。但你可能想要在其上实现描述方法。

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

(我修正了你的方法案例,尽管+1。) – Wevah 2011-03-17 20:02:04