IPhone TableView没有填充JSON数据

时间:2011-12-28 00:50:10

标签: objective-c cocoa-touch iphone-sdk-3.0

我有一个包含tableview的页面 - 以及一个将邮政编码发送到PHP页面并返回JSON数据的文本字段和按钮。我无法使用返回的数据填充表视图。 NSLog显示正在返回数据,但表仍为空白。没有错误。 代码:

- (IBAction) searchzip: (id) sender
{
NSString *post = [NSString stringWithFormat:@"zip=%@", zipField.text];
NSString *hostString =     @"https://www.mysite.com/searchzip.php?";

// Append string and add percent escapes
hostString = [[hostString stringByAppendingString:post] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *hostURL = [NSURL URLWithString:hostString];
NSString *jsonString = [[NSString alloc] initWithContentsOfURL:hostURL];
self.zipArray = [jsonString JSONValue]; 
NSLog(@"%@", zipArray);
[jsonString release];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section    {
return [zipArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
NSDictionary *infoDictionary = [self.zipArray objectAtIndex:indexPath.row];
static NSString *Prospects = @"agencyname";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Prospects];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:Prospects]   autorelease];
}

// setting the text
cell.text = [infoDictionary objectForKey:@"agencyname"];    
self.navigationItem.title = @"Zip Search";

// Set up the cell
return cell;

}

标题文件:

@interface SearchZipViewController : UITableViewController{
NSMutableArray *zipArray;
IBOutlet UITextField *zipField;
IBOutlet UIButton *searchButton;
}
@property (nonatomic, retain) NSMutableArray *zipArray;
@property (nonatomic, retain) UITextField *zipField;
@property (nonatomic, retain) UIButton *searchButton;
- (IBAction) searchzip: (id) sender;
@end

3 个答案:

答案 0 :(得分:2)

我认为基本问题是您正在尝试构建复合视图(textfield,button和tableview)并使用UITableViewController作为控制器。它在SO和其他地方被引用,这基本上是禁止的。相反,尝试类似:

@interface SearchZipViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> {
    IBOutlet UIButton* searchButton;
    IBOutlet UITextField* zipField;
    IBOutlet UITableView* tableView;
}

@end

然后将IB中的UITableView连接到文件所有者中的tableView ivar - 从您的评论中可以看出,您试图将复合视图中的表视图元素连接到文件的所有者,UIViewController - 不是你想要的。

答案 1 :(得分:0)

在搜索zip方法结束时,您应该添加以下行:

[tableView reloadData];

否则你的tableView无法知道你有新的数据要显示。

答案 2 :(得分:0)

您应该使用cell.textLabel.text来设置表格单元格的文本。不推荐使用text属性。

另外,尝试在该行上设置断点以确保您所拥有的局部变量实际上具有您期望的值(即正确的JSON值)。也许你的一个关键字符串(如外壳)中有拼写错误?