CellForRowAtIndexPath not called - UITableViewCells disappear/are blank

时间:2015-07-28 23:46:34

标签: ios objective-c xcode debugging

Posting a specific question/answer to a specific problem (unlike the general problems with this method I've seen elsewhere):

I have a dgemm, which is a part of a custom UITableView, which I setup and then add to a different view controller.

My UITableViewController is being loaded, calls all the appropriate setup methods (e.g. numberOfRowsInSection, numberOfSectionsInTableView, etc), but UITableView is never called.

I've confirmed that the dataset is being loaded - cellForRowAtIndexPath is not always zero.

What gives??

2 个答案:

答案 0 :(得分:1)

目标似乎是重用表视图的数据源。这可以通过将数据源与视图控制器分离来实现。概括如下:

// MyTableViewDatasource.h
@interface MyTableViewDatasource : NSObject <UITableViewDatasource> 

@property(strong,nonatomic) NSMutableArray *array;

@end

// MyTableViewDatasource.m

#import "MyTableViewDatasource.h"

@implementation MyTableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)s {
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // your cell config logic from the original view controller
    // replace any mention of that vc's model array with self.array
}

@end

现在,说ViewControllerA有一个tableView,我们希望它的数据源是我们新定义的数据源......

// ViewControllerA.m

#import "ViewControllerA.h"
#import "MyTableViewDatasource.h"

@interface ViewControllerA ()

@property(strong,nonatomic) MyTableViewDatasource *datasource;

@end

-(void)viewDidLoad {
    // create our data and our datasource
    // don't have to do this in viewDidLoad, but it needs to be done
    // before the table can be seen, anytime after the model is ready
    // this "model" in your case is whatever array that holds the data for the table
    NSMutableArray *model = [@[@"Moe", @"Larry", @"Curly"] mutableCopy];

    MyTableViewDatasource *datasource = [[MyTableViewDatasource alloc] init];
    datasource.array = model;
    self.tableView.datasource = datasource;
}

现在,ViewControllerA,无论它曾经修改过它的模型数组,都应该这样做......

[self.datasource.array addObject:@"Shemp"];
[self.tableView reloadData];

希望很明显ViewControllerB和C等可以做同样的事情,替换你在答案中发布的代码。

答案 1 :(得分:0)

If you are using ARC, then it's very likely that your custom view controller, which is the ultimate owner of your UITableView, it being trashed as soon as you add the tableView to another view.

Try adding the UITableView's view controller to the master/other view controller's, either via a property or through the view hierarchy.

In my case, I simply created a new property for it in the view controller that wanted its table:

for item in range(len(split_text)):
        if item == word:
            split_text[item] = ("*" * length)
            ...

and later assigned it to self when creating it:

@property (strong, nonatomic) MyTableViewController *tvc;