Обновить вид таблицы?

Я думаю, что у меня довольно простая задача, но почему-то она не хочет работать. Я новичок в objective-c, поэтому я предполагаю, что это всего лишь небольшая ошибка. Я до сих пор не знаю, что я делаю, в настоящее время он больше похож на программу копирования и вставки. Как я не знаю, нужен ли мне IBOutlet в интерфейсе или как свойство или как то и другое.

Что у меня:

A ViewController с кнопкой, меткой и представлением таблицы. Кнопка подключается к серверу sharepoints и считывает список и добавляет значение в массив. Эта часть работает.

Разъем делегата и источника данных подключен к контроллеру просмотра.

Что я хочу:

Массив должен быть источником данных Table View, поэтому я просто хочу, чтобы он обновился после того, как я прочитал новые данные в массиве. Появляются тестовые данные, которые я добавляю в функцию viewDidLoad к массиву. Поэтому я предполагаю, что каким-то образом связал массив с табличным представлением.

Я дам вам полный код:

ViewController.h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    IBOutlet UILabel *output;
    IBOutlet UITableView *tableView;
    NSMutableData *webData;
    NSString *finaldata;
    NSString *convertToStringData;
    NSMutableString *nodeContent;
}
@property (nonatomic, retain) UILabel *output;
@property (nonatomic, weak) IBOutlet UITableView *tableView;
-(IBAction)invokeService:(UIButton *) sender;

@end

ViewController.m:

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *foundUrlaub;
}

@end

@implementation ViewController

@synthesize output;


- (void)viewDidLoad
{
    [super viewDidLoad];

    // SOME TEST DATA... THIS SHOWS UP IN MY TABLE VIEW
    foundUrlaub = [[NSMutableArray alloc]init];
    [foundUrlaub addObject:@"first cell"];
    [foundUrlaub addObject:@"second cell"];
    [foundUrlaub addObject:@"third cell"];
}

-(IBAction)invokeService:(UIButton *) sender
{
    // connection to sharepoint
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"didReceiveResponse");
    [webData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData");
    [webData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with the Connection");
    NSLog(error.description);
}

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    NSLog(@"canAuthenticateAgainstProtectionSpace");
    return YES;
}

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"didReceiveAuthenticationChallenge");
    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"XXXXXX" password:@"XXXXXX" persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"DONE. Received Bytes: %d", [webData length]);
    convertToStringData = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=ows_Title=')(.*)(?=' ows_MetaInfo)" options:0 error:NULL];

    NSArray *matches = [regex matchesInString:convertToStringData options:0 range:NSMakeRange(0, [convertToStringData length])];

    // HERE I LOAD SOME DATA IN THE ARRAY
    [foundUrlaub removeAllObjects];
    for (NSTextCheckingResult *match in matches)
    {
        NSRange matchRange = [match rangeAtIndex:1];
        NSString *matchString = [convertToStringData substringWithRange:matchRange];
        NSLog(@"Match: %@", matchString);
        [foundUrlaub addObject:matchString]; // <- ADDS 3 STRINGS TO ARRAY
    }

    // THIS DOES NOT WORK!
    [tableView reloadData];

}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [foundUrlaub count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"TableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [foundUrlaub objectAtIndex:indexPath.row];
    return cell;
}

@end

Ответы

Ответ 1

попробуйте использовать [_tableView reloadData]; Вы не @synthesize ваш tableView в своем .m, поэтому вам нужно использовать автосинтетический идентификатор

Ответ 2

Ваш код выглядит отлично,

убедитесь, что

  • IBOutlet для tableView правильно подключен
  • Источник данных и делегаты из nib подключены к владельцу файлов

Необходимо смотреть и читать для вас

Ответ 3

Вам необходимо подключить Outlet в Interfacebuilder к вашему UITableview tableView.

Ответ 4

Вы пытаетесь перезагрузить таблицу из отдельного потока. поэтому UIView можно изменить только из основного потока, так что сделайте что-то вроде этого:

[tableView performSelectorOnMainThread:@selector(reloadData)
                            withObject:nil
                         waitUntilDone:YES];