2012-04-02 28 views
0

首先,我是新來的Objective-C編程,所以我可能在我的代碼中犯了一些錯誤。從MySQL到NSTableView的NSArray

以下是我所做的:我用一些xml創建了一個php文件,以從我的MySQL數據庫獲取值。一切都進入Objective-C的NSArray。如果我看看日誌,一切工作正常,因爲它顯示我的陣列,每一個MySQL的行和列這樣的:

2012-04-02 08:20:14.822 POS[64632:707] (

    { 
    CPU = 0; 
    TPS = "(null)"; 
    TVQ = "(null)"; 
    consigne = 0; 
    coutantQuantiteRecue = 0; 
    description = ""; 
    nom = ""; 
    prixProduit = 0; 
    quantiteRecue = 0; 
    stock = 0; 
}, 
    { 
    CPU = 768; 
    TPS = "(null)"; 
    TVQ = "(null)"; 
    consigne = 0; 
    coutantQuantiteRecue = 0; 
    description = ""; 
    nom = hhh; 
    prixProduit = 0; 
    quantiteRecue = 0; 
    stock = 0; 
}, 

2012-04-02 08:20:14.836 POS[64632:707] The number of rows is:2 

的問題是,我在我的TableView中唯一得到的是這樣的每個單元{

Table View example image

這裏是我的.h:

@interface InventoryManagement : NSObject<NSApplicationDelegate, NSTableViewDataSource> 
{ 
IBOutlet NSTableView* inventoryTable; 
NSArray* m_items; 

} 
-(int)numberOfRowsInTableView:(NSTableView *)inventoryTable; 
-(id)tableView:(NSTableView *)inventoryTable objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex; 
-(void)dealloc; 

@property (retain) NSArray* m_items; 

@end 

這是我的.m文件:

@implementation InventoryManagement 

@synthesize m_items; 

-(id)init 
{ 
[super init]; 

NSInteger index = 0; 
NSString *urlString = [NSString stringWithFormat:@"http://localhost:8888/php/getProducts.php?index=%d&", index]; 
m_items = [NSArray arrayWithContentsOfURL:[NSURL URLWithString: urlString]]; 
NSLog(@"%@", [m_items description]); 
[m_items retain]; 
[inventoryTable reloadData]; 
return self; 
} 



-(int)numberOfRowsInTableView:(NSTableView *)inventoryTable 
{ 

NSLog(@"The number of rows in fullResult is:%i", [m_items count]); 
return [m_items count]; 



} 

-(id)tableView:(NSTableView *)inventoryTable objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex 
{ 

return [m_items objectAtIndex:rowIndex]; 

} 

-(void)dealloc 
{ 
[m_items release]; 
[super dealloc]; 
} 

@end 

我的對象很好地連接到我的TableView的dataSource和委託。我想要這些單元格填充我的數據庫值。

回答

1

看看可可綁定未來的作品。他們都是偉大的。

關於你的問題:問題出在方法

-(id)tableView:(NSTableView *)inventoryTable objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex 
{ 

return [m_items objectAtIndex:rowIndex]; 

} 

你全部退回對象,即:

{ CPU = 768; TPS =「(null)」; TVQ =「(null)」; consigne = 0; coutantQuantiteRecue = 0; description =「」; nom = hhh; prixProduit = 0; quantiteRecue = 0; stock = 0; }

這是一個字符串。 您必須檢查tableColumn變量並僅返回正確的信息:例如quantiteRecue,CPU等。

這樣做的最好方法是在ObjectiveC中創建一個Model類,它封裝了一行數據庫。然後你的m_items數組將包含你的Model類,並且你可以返回正確的屬性而不用每次都解析字符串...

+0

你說得對。我沒有意識到。我會試一試,稍後發佈我的結果。謝謝! – 2012-04-02 15:47:37

+0

我實際上做的是創建一個「for」循環,並將每個列單元格插入一個字符串[]和另一個循環以將這些字符串插入數組[]。 – 2012-04-08 23:29:06