我有一个 UITableView,我想通过 WebAPI 填充数据。我已经完成了所有设置,并且可以验证数据是否以 JSON 格式返回。我不明白为什么我在使用 NSLog 时看到我的数组中的数据打印了好几次,以及如何将这些数据分配给 UITableView。我能够从 viewDidLoad 方法填充表,但这些是硬编码值。我想用从我对远程服务器的调用返回的数据填充网格。我可以在我的 didReceiveData 委托中获得这些数据。我在这里做错了什么?
我的 MasterViewControler.h 中有这段代码
@interface MasterViewController : UITableViewController <UITableViewDataSource, UIAlertViewDelegate> {
NSMutableArray *dataArray;
NSMutableArray *categoryNames;
}
这是我在 MasterViewController.m 文件中的精简版
NSMutableData* receivedData;
NSString* hostName;
NSInteger portNumber = 9999;
NSMutableDictionary* dictionary;
NSInteger maxRetryCount = 5;
int count = 0;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"Succeeded! Received %d bytes of data",[data length]);
NSError *error = nil;
// Get the JSON data from the website
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if ([result isKindOfClass:[NSArray class]]) {
for (NSArray *item in result)
[dataArray addObject:item];
NSLog(@"%@", dataArray);
}
else {
NSDictionary *jsonDictionary = (NSDictionary *)result;
for(NSDictionary *item in jsonDictionary)
NSLog(@"Item: %@", item);
}}
- (void)viewDidLoad{
[super viewDidLoad];
hostName = [[NSString alloc] initWithString:@"12.34.56.78"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%i%@", hostName, portNumber, @"/api/products"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 2];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewItem)]; //insertNewObject
self.navigationItem.rightBarButtonItem = addButton;
dataArray = [[NSMutableArray alloc] init];
//[dataArray addObject:@"Apple"];
//[dataArray addObject:@"Mango"];
//[dataArray addObject:@"Orange"];}
我没有在此处填充 dataArray,而是尝试在 didReceiveData 委托中填充它。dataArray 将被分配,但几乎就像我必须重新加载 UITableView 才能查看值。我在 didReceiveData 结束时尝试过,但收到错误。