问题很简单:如何UITableViewCell从Xib文件加载自定义?这样做允许您使用Interface Builder来设计单元格.由于内存管理问题,答案显然并不简单.这个主题提到了这个问题并建议了一个解决方案,但是在NDA发布之前并且没有代码.这是一个很长的线程,在没有提供明确答案的情况下讨论了这个问题.
这是我用过的一些代码:
static NSString *CellIdentifier = @"MyCellIdentifier";
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
cell = (MyCell *)[nib objectAtIndex:0];
}
Run Code Online (Sandbox Code Playgroud)
要使用此代码,请创建MyCell.m/.h,它是所需组件的新子类UITableViewCell并添加IBOutlets.然后创建一个新的"空XIB"文件.在IB中打开Xib文件,添加一个UITableViewCell对象,将其标识符设置为"MyCellIdentifier",并将其类设置为MyCell并添加组件.最后,连接IBOutlets到组件.请注意,我们没有在IB中设置文件所有者.
如果未通过其他工厂类加载Xib,则其他方法主张设置文件所有者并警告内存泄漏.我在Instruments/Leaks下测试了上面的内容,没有发现内存泄漏.
那么从Xibs加载单元格的规范方法是什么?我们设置文件的所有者吗?我们需要工厂吗?如果是这样,工厂的代码是什么样的?如果有多种解决方案,让我们澄清每种解决方案的优缺点......
在用于iPhone的Objective-C编码中使用IBAction和IBOutlet的目的是什么,如果我不使用它会有什么不同吗?
我知道这个问题是在50次之前被问到的,但是我已经仔细研究了所有其他答案,但没有找到任何可以解决我问题的方法。
无论如何,这是我的代码:
NSMutableArray *cellIndicesToBeDeleted = [[NSMutableArray alloc] init];
for (int i = 0; i < [thetableView numberOfRowsInSection:0]; i++) {
NSIndexPath *p = [NSIndexPath indexPathForRow:i inSection:0];
if ([[thetableView cellForRowAtIndexPath:p] accessoryType] == UITableViewCellAccessoryCheckmark) {
[cellIndicesToBeDeleted addObject:p];
[self.cellArray removeObjectAtIndex:i];
}
}
[thetableView deleteRowsAtIndexPaths:cellIndicesToBeDeleted withRowAnimation:UITableViewRowAnimationLeft];
[cellIndicesToBeDeleted release];
Run Code Online (Sandbox Code Playgroud)
当我执行这段代码时,我得到了这个崩溃日志:
Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the …Run Code Online (Sandbox Code Playgroud) ios ×2
uitableview ×2
cocoa-touch ×1
datasource ×1
ibaction ×1
iboutlet ×1
iphone ×1
objective-c ×1
xib ×1