非常熟悉Android编程,但对iOS(和Objective-C)来说是非常新的。
我在我的应用程序中调用一个远程php文件,并且(我相信)根据我的NSLOG结果成功解析了JSON结果。例如:
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 :(得分:5)
使用NSDictionary
方法访问objectForKey
中的对象。例如,要在字典中获取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