虽然我怀疑真正的问题可能隐藏在其他地方,但我在使用UINib时还是有一些奇怪的事情发生。
我的应用程序使用的是一个表格视图,由于其复杂性,这些单元格的内容已经在Interface中准备好了。对于新的单元格(相对于重用的单元格),使用UINib类实例化nib的内容。由于只有一个nib用于所有单元格,并且为了减少每次加载文件的开销,我将UINib作为属性cellNib添加到视图控制器子类中,在viewDidLoad的实现中加载该子类一次。
现在是奇怪的部分。一切都很好,表视图中填充了它的数据,所有单元格都按照应有的方式设置了nib的内容。但是,只要我一滚动表视图,应用程序就会崩溃。
调用堆栈给出了以下内容:-NSCFNumber实例化wrong :options::un为人识别的选择器发送到实例显然,用于实例化来自cellNib的内容的消息再次被发送到错误的对象。消息被发送到的对象时有发生变化,因此有一些随机发生的事情。
我不明白-为什么它在加载表视图时工作了大约10次,但是当表视图被滚动时就不再起作用了?
如果我每隔一段时间创建一个UINib 的新实例(如下面的代码所示),那么一切都很正常,包括滚动。
我在哪里犯错误?我的UINib属性的指针会丢失吗?如果是,为什么?
下面是我使用的代码(为了便于阅读,我删除了所有的数据加载和其他东西):
@interface NTDPadViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSManagedObjectContext *managedObjectContext;
NSMutableArray *ntdArray;
IBOutlet UITableView *ntdTableView;
UINib *cellNib;
}
@property(nonatomic,retain) NSManagedObjectContext *managedObjectContext;
@property(nonatomic,retain) NSMutableArray *ntdArray;
@property(nonatomic,retain) UITableView *ntdTableView;
@property(nonatomic,retain) UINib *cellNib;
@end执行情况:
@implementation NTDPadViewController
@synthesize managedObjectContext;
@synthesize ntdArray;
@synthesize ntdTableView;
@synthesize cellNib;
-(void)viewDidLoad {
[super viewDidLoad];
cellNib = [UINib nibWithNibName:@"NTDCell" bundle:nil];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell setBackgroundColor:[UIColor clearColor]];
// These two should work equally well. But they don't... of course I'm using only one at a time ;)
// THIS WORKS:
UINib *test = [UINib nibWithNibName:@"NTDCell" bundle:nil];
NSArray *nibArray = [test instantiateWithOwner:self options:nil];
// THIS DOESN'T WORK:
NSArray *nibArray = [cellNib instantiateWithOwner:self options:nil];
[[cell contentView] addSubview:[nibArray objectAtIndex:0]];
}
return cell;
}非常感谢!!
发布于 2010-09-17 09:40:59
这一行将autoreleased实例分配给cellNib
cellNib = [UINib nibWithNibName:@"NTDCell" bundle:nil];这意味着使用以下一行:
NSArray *nibArray = [cellNib instantiateWithOwner:self options:nil];. cellNib在其关联的自动释放池被耗尽时已经被释放,使用它将导致未定义的行为。
如果您希望cellNib保持在周围,那么就拥有它的所有权,例如通过使用声明的属性:
self.cellNib = [UINib nibWithNibName:@"NTDCell" bundle:nil];https://stackoverflow.com/questions/3734157
复制相似问题