0

这是我针对这个特定视图控制器的所有代码。正如这个问题的标题所述,我看到我的 UITableView 一次又一次地加载了相同的 9 个值。如果我在 connectionDidFinishLoading 中放置一个断点并等待一秒钟,我只会看到一次呈现到表视图的数据。我已经尝试了各种方法来解决这个问题;非常感谢您的帮助。

@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
4

1 回答 1

0

willSendRequestForAuthenticaiton 是一个委托方法。然而,在您的委托方法中,您正在生成一个全新的 URL 请求,该请求又由 willSendRequest 委托处理,该委托会生成另一个请求等,从而不断地用数据填充您的 dataArray。

摆脱委托方法中的 url 请求,它应该会为您解决问题。

于 2012-06-25T20:54:01.693 回答