WebAPI を介してデータを入力したい UITableView があります。すべての設定が完了し、データが 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 の最後でそれを試しましたが、エラーが発生しました。