如何将数据从UIVIewController传递到TableView子视图?

时间:2014-11-07 15:08:02

标签: ios objective-c uitableview subview

我是ios编程的新手,我正在尝试编写一个视图控制器,它将在视图的顶部显示一个问题(通过标签),然后在下面的tableview子视图中显示一个答案列表。该视图是使用界面构建器设置的,但我以编程方式添加了tableview。

我可以从JSON源加载数据并使用滑动手势将其打印出来,但无法在我的表视图中访问数据。我知道从NSLog开始,numberOfRowsInSection在开始时运行一次返回0但是当我调用[self.tableView reloadData]时不会再次运行,这意味着表仍然认为它有0行,即使它应该有大约20行。将UIViewController设置为表视图委托和数据源。我还需要做什么?

主要问题:当该表视图是我的视图控制器的子视图时,如何访问表视图函数中的视图控制器的NSMutablearray属性?谢谢!

这是我的初始声明和设置:

@interface BNRJudgeViewController () <UITextFieldDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate, UITableViewDataSource, UITableViewDelegate >    
@property (nonatomic, strong) NSURLSession *session;
@property (weak, nonatomic) IBOutlet UILabel *question;
@property (weak, nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *answerArray;
@end

@implementation BNRJudgeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if ([self isKindOfClass:[UIViewController class]]) {
        if(self){
            // Custom initialization
            self.title=@"Judge";
            self.navigationController.navigationItem.title = @"Judge";
            self.answerArray = [[NSMutableArray alloc] init];
            NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
            _session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
            CGRect frame = CGRectMake(61, 252, 200, 225);
            UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
            tableView.delegate = self;
            tableView.dataSource = self;
            [self.view addSubview:tableView];
        }

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([self isKindOfClass:[UIViewController class]]) {
        [self fetchFeed];
    }

    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    rightSwipe.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:rightSwipe];

    UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
    leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    leftSwipe.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:leftSwipe];

}

这是我获取JSON数据并将其分配给视图控制器的NSMutableArray属性的地方:

- (void)fetchFeed
{

    NSString *requestString = @"http://wsomeurl";
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    NSURLSessionDataTask *dataTask =
    [self.session dataTaskWithRequest:req completionHandler:
     ^(NSData *data, NSURLResponse *response, NSError *error){

         NSMutableArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                        error:nil];

         self.answerArray = jsonObject;
        // NSLog(@"%@", self.answerArray);
               dispatch_async(dispatch_get_main_queue(), ^{
         [self.tableView reloadData];
               });


     }];
        [self.tableView reloadData];
    [dataTask resume];
    [self.tableView reloadData];
}

以下是我的tableview所需函数,在我的视图控制器中实现:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"recent integer count is %d", [self.answerArray count]);
    return [self.answerArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
 //   NSDictionary *cellD = self.answerArray[indexPath.row];
   NSLog(@"%@", self.answerArray);
    NSLog(@"hi hi!");
     //  NSLog(@"%@", [cellD objectForKey:@"username"]);
 //   cell.textLabel.text = [cellD objectForKey:@"username"];
    return cell;

}

最后这里有一些滑动函数显示这些函数可以看到数组 - 它只是表视图函数不是。

- (void)swipeRight:(UISwipeGestureRecognizer *) gr
{
    NSLog(@"right swipe worked");
    NSLog(@"right swipe array count is %d", [self.answerArray count]);

}

- (void)swipeLeft:(UISwipeGestureRecognizer *) gr
{
    NSLog(@"left swipe worked");
    NSLog(@"left swipe array count is %d", [self.answerArray count]);

}

对不起,很长的帖子。主要问题:如何在表格视图函数中访问视图控制器的NSMutablearray属性?谢谢!


额外的技术相关问题/评论......我重新编写了一个自定义tableviewcontroller类来加载这些数据并具有正确的大小和位置,然后在我的视图控制器中初始化此tableview控制器类并将其视图作为子视图。但我不想在两个视图控制器之间传递数据,因为我想尽可能干净地在视图上滑动来更新视图和子视图......但这可能是更好的方法吗?

两个相关的技术问题。首先,将这些信息填充到我可以从任何视图控制器访问的单例类中更有意义吗?第二,编写一些协议(没有这样做,只知道它)更有意义将信息强制重新加载到正确的位置吗?)作为一个新手,我认为这两个都比较简单而不仅仅是坚持我正在努力做一个视图控制器,但我可能还不太了解目标c。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的init方法中有UITableView *tableView = [[UITableView alloc] initWithFrame:frame];,因此tableView是一个局部变量。在其他地方你有[self.tableView reloadData],但是你从未将你的属性分配给表视图,所以self.tableView是零。您应该将init方法中的代码更改为

        _tableView = [[UITableView alloc] initWithFrame:frame];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];