从MySQL到NSTableView的NSArray

时间:2012-04-02 13:56:50

标签: mysql objective-c cocoa nsarray nstableview

首先,我是Objective-c编程的新手,所以我可能在代码中犯了一些错误。

这就是我所做的:我创建了一个带有一些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 个答案:

答案 0 :(得分:1)

看看Cocoa Bindings的未来作品。他们很棒。

关于你的问题:问题出在方法

-(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;       股票= 0; }

这是一个字符串。 您必须检查tableColumn变量并仅返回正确的信息:例如quantiteRecue,CPU等。

执行此操作的最佳方法是在ObjectiveC中创建一个包含数据行的模型类。然后你的m_items数组将包含你的Model类,你可以返回正确的属性,而不是每次都解析字符串......