2013-01-17 48 views
1

非常熟悉Android編程,但對於iOS(和Objective-C)來說非常新穎。使用NSDictionary填充UITableView包含從MySQL數據庫分析的JSON數據

我在我的應用程序和(我相信)根據我的NSLOG結果成功解析JSON結果調用遠程php文件。例如:

2013-01-17 14:24:30.611 JSON TESTING 4[1309:1b03] Deserialized JSON Dictionary = { 
products =  (
      { 
     BF = ""; 
     EN = "2342"; 
     Measure = ft; 
     Name = "Brian"; 
     "Name_id" = 1; 
     Home = "New York"; 
     "DB_id" = 1; 
    }, 
      { 
     BF = ""; 
     EN = "2123"; 
     Measure = ft; 
     Name = "Rex"; 
     "Name_id" = 3; 
     Home = "New York"; 
     "DB_id" = 5; 
    } 
); 
success = 1; 

}

我的問題在於如何填充此信息到表視圖。我可以自定義一個原型單元格,但我從哪裏去?

編輯:

這裏是我的視圖設置代碼:

#pragma mark - Table View 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return productArray.count; 
    NSLog(@"Number of arrays %u", productArray.count); 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    } 


    NSDictionary *productDictionary = [productArray objectAtIndex:indexPath.row]; 
    cell.textLabel.text = [productDictionary objectForKey:@"BF"]; 

    return cell; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self launchTest]; 
} 

和我的.h文件

@interface tpbaMasterViewController : UITableViewController 
{ 
    NSDictionary *lists; 
    NSArray *productArray; 
} 

- (void) launchTest; 

@property (strong, nonatomic) IBOutlet UITableView *tableView; 



@end 
+0

lists =(NSDictionary *)jsonObject; productArray = [列出objectForKey:@「products」]; – ADK

回答

5

您使用objectForKey方法訪問一個NSDictionary的對象。例如,爲了獲得產品的NSArray在詞典:

NSArray *productArray = [myDictionary objectForKey:@"products"]; 

現在你有兩個字典對象的數組。對於各種UITableViewDataSource方法,您可以查詢數組。幾個例子:

對於– tableView:numberOfRowsInSection:,返回在數組中的對象的數目:

`return productArray.count;` 

而對於tableView:cellForRowAtIndexPath:

NSDictionary *productDictionary = [productArray objectAtIndex:indexPath.row]; 
    myCell.bfLabel.text = [productDictionary objectForKey:@"BF"]; 
    myCell.enLabel.text = [productDictionary objectForKey:@"EN"]; 
    // continue doing the same for the other product information 

在.m文件聲明productArray如下所示品牌它在您的視圖控制器內可見(假定productDictionary是屬性:

@interface MyCollectionViewController() { 
    NSArray *productArray; 
} 
@end 
... 
@implementation MyCollectionViewController 

    -(void)viewDidLoad{ 
     [super viewDidLoad]; 

     productArray = [self.myDictionary objectForKey:@"products"]; 
    } 
... 
@end 
+2

使用新的Objective-C語法,您可以將[myDictionary objectForKey:@「products」]編寫爲myDictionary [@「products」] – jsd

+0

感謝您的支持。我在哪裏聲明我的NSArray * productArray在我的UITableViewDataSource方法中使用它? – ADK

+0

@ADK - 您可以在.m文件的接口塊中聲明它。更新我的答案以表明這一點。 – bobnoble