2012-06-25 5 views
0

이 특정보기 컨트롤러에 대한 모든 코드가 여기에 있습니다. 이 질문의 제목으로 내 UITableView 같은 9 값을 반복적으로로드 된보고있다. connectionDidFinishLoading에 중단 점을 배치하고 1 초를 기다리는 경우 테이블보기에 렌더링 된 데이터 만 표시됩니다. 나는 이것을 해결하기 위해 여러 가지 일을 시도했다. 도움이 대단히 감사합니다.UITableView가 여러 번로드되었습니다. 도움이 필요합니다. 이유를 모르겠다.

@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 
+0

이제 모든 NSLog()의 출력은 어떻게됩니까? –

답변

0

willSendRequestForAuthenticaiton은 대리자 메서드입니다. 그러나 대리자 메서드 내에서 새로운 URL 요청을 생성하고 willSendRequest 대리자가 처리합니다. 그러면 다른 요청 등이 생성되어 데이터 배열에 데이터를 계속 채 웁니다.

위임 메서드에서 url 요청을 제거하면 문제가 해결됩니다.

+0

MikeS, 정말 고마워요! 나는 이것을 약간의 시간 동안 고투하고 있었다!! – brianhevans

관련 문제