当我初始化自定义单元格时,它没有设置为'[(super或self)init ...]'的结果时返回'self'

Ale*_*xey 6 iphone xcode init uitableview ios

在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;
}
Run Code Online (Sandbox Code Playgroud)

在方法cellForRowAtIndexPath中的MyTableViewController.m中,我初始化我的自定义单元格

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

cell=[[CustomCell alloc]init];
return cell;
Run Code Online (Sandbox Code Playgroud)

}

一切都按照我的预期运作,但当我做的时候,Product -> Analyse我得到了
Returning 'self' while it is not set to the result of '[(super or self) init...]'
我做错了什么?

jrt*_*ton 8

您正在使用从数组返回的对象覆盖self(返回super init).如果要从nib加载自定义单元格,请在cellForRowAtIndexPath方法中执行此操作,或者在从nib加载的自定义单元格上创建一个便捷类方法:

在你的cellForRowAtIndexPath中:

cell = [CustomCell cell];
Run Code Online (Sandbox Code Playgroud)

在您的单元格的实现中:

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

编辑 - 更改了方法名称,因为new*表示将返回保留的对象.


sEl*_*yan 7

保持您的init方法如下,并在Interface Builder中进行链接

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

    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

- (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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)