Возвращая 'self', пока он не установлен в результат '[(super или self) init ...]', когда я инициализирую пользовательскую ячейку - PullRequest
6 голосов
/ 18 января 2012

В CustomCell.m я определяю метод init, где я хочу загрузить ячейку из IB:

- (id)init {
    self = [super init];
    if (self) {
        NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        self = [nib objectAtIndex:0];

    }
    return self;
}

В MyTableViewController.m в методе cellForRowAtIndexPath я инициализирую свою пользовательскую ячейку

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

cell=[[CustomCell alloc]init];
return cell;

}

Все работает, как я ожидал, но когда я сделал Product -> Analyse я получаю
Returning 'self' while it is not set to the result of '[(super or self) init...]'
Что я делаю не так?

Ответы [ 4 ]

8 голосов
/ 18 января 2012

Вы перезаписываете self (возвращается из super init) объектом, возвращенным из вашего массива.Если вы хотите загрузить пользовательскую ячейку из пера, сделайте это в вашем методе cellForRowAtIndexPath или создайте метод вспомогательного класса для своей пользовательской ячейки, который загружается из пера:

В вашем cellForRowAtIndexPath:

cell = [CustomCell cell];

В реализации вашей ячейки:

+(CustomCell*)cell
{
    NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];         
    return [nib objectAtIndex:0];
}

EDIT - изменено имя метода, поскольку new * указывает, что сохраненный объект будет возвращен.

7 голосов
/ 18 января 2012

Сохраните метод init, как показано ниже, и выполните связывание в Интерфейсном Разработчике

- (id)init {
    self = [super init];
    if (self) {

    }
    return self;
}

И

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

    CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];

        for (id currentObject in topLevelObjects){
            if ([currentObject isKindOfClass:[UITableViewCell class]]){
                cell =  (CustomCell *) currentObject;
                break;
            }
        }
    }
}
1 голос
/ 07 апреля 2015

Я столкнулся с той же проблемой, я исправил ее, удалив код, похожий на

NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];         
return [nib objectAtIndex:0];

из метода инициализации определения CustomView.

Поместите этот код в место, где вы создаете Custom.

1 голос
/ 18 января 2012

То, что я делаю, это

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) 
    {
        // Initialization code.
        //
        UITableViewCell *view = [[[NSBundle mainBundle] loadNibNamed:@"SmallCellView" owner:self options:nil] lastObject];
        self.backgroundView = view;
}
    return self;
}

тогда в основной класс

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

    SmallCellView *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[SmallCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
 }
  return cell;
}

Для меня это работает нормально и в Product -> Analyse не выдает никаких предупреждений или ошибок

...