これが、この特定のView Controllerのすべてのコードです。この質問のタイトルにあるように、UITableView に同じ 9 つの値が何度も読み込まれています。connectionDidFinishLoading にブレークポイントを配置して 1 秒待つと、テーブル ビューにレンダリングされたデータが 1 回だけ表示されます。これを解決するためにあらゆる種類のことを試しました。助けていただければ幸いです。
@implementation MasterViewController
@synthesize response;
NSMutableData* receivedData;
NSString* hostName;
NSInteger portNumber = 9999;
NSMutableDictionary* dictionary;
NSInteger maxRetryCount = 5;
int count = 0;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"Succeeded! Received %d bytes of data",[data length]);
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
receivedData = nil;
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
if ([result isKindOfClass:[NSArray class]]) {
for (NSArray *item in result) {
NSArray *category = [item valueForKey:@"CategoryName"];
[dataArray addObject:category];
}
}
else {
NSDictionary *jsonDictionary = (NSDictionary *)result;
for(NSDictionary *item in jsonDictionary)
NSLog(@"Item: %@", item);
}
connection = nil;
[self.tableView reloadData];
NSLog(@"Finished");
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return YES;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return YES;
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSString* username = @"test";
NSString* password = @"testPwd";
NSLog(@"Attempting connection with username: %@", username);
NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", username, password];
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", loginString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%i%@", hostName, portNumber, @"/api/categories"]];
NSLog(@"URL: %@", url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 1.0];
[request addValue:authHeader forHTTPHeaderField:@"Authorization"];
[NSURLConnection connectionWithRequest:request delegate:self];
if ([challenge previousFailureCount] <= maxRetryCount) {
NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
NSLog(@"Failure count %d",[challenge previousFailureCount]);
}
}
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewItem)];
self.navigationItem.rightBarButtonItem = addButton;
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
- (void)addNewItem
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Product"
message:@"Enter the new product name"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert)
{
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *object = [dataArray objectAtIndex:indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
UITextField *textField = [alertView textFieldAtIndex:0];
[dataArray addObject:textField.text];
[self.tableView reloadData];
NSLog(@"Plain text input: %@",textField.text);
NSLog(@"Alert View dismissed with button at index %d",buttonIndex);
}
- (void)viewWillAppear:(BOOL)animated {
self.title = @"Categories";
receivedData = [[NSMutableData alloc] init];
hostName = [[NSString alloc] initWithString:@"12.234.56.123"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%i%@", hostName, portNumber, @"/api/categories"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 1.0];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
} else {
}
dataArray = [[NSMutableArray alloc] init];
}
@end