2011-03-17 31 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