gpt4 book ai didi

iphone - 使用 UINib/指针擅离职守的奇怪问题

转载 作者:太空狗 更新时间:2023-10-30 04:01:38 25 4
gpt4 key购买 nike

我在使用 UINib 时遇到了一些奇怪的事情,尽管我怀疑真正的问题可能隐藏在其他地方。

我的应用程序使用的是表格 View ,由于单元格的复杂性,其内容已在 Interface Builder 中准备好。对于新单元格(与重复使用的单元格相反), Nib 的内容使用 UINib Class 实例化。 .因为只有一个 Nib 用于所有单元格并减少每次加载文件的开销,所以我将 UINib 作为属性 cellNib 添加到我的 viewcontroller 子类中,我在 viewDidLoad 的实现中加载了一次.

现在是奇怪的部分。一切正常,tableview 填充了它的数据,所有单元格都设置了 nib 的内容。但是只要我滚动表格 View ,应用程序就会崩溃。
调用堆栈泄露了这一点:-[NSCFNumber instantiateWithOwner:options:]: unrecognized selector sent to instance显然,从 cellNib 再次实例化内容的消息已发送到错误的对象。消息发送到的对象时常不同,因此有些事情是随机发生的。

我不明白 - 为什么它在加载 tableview 时工作了大约 10 次,但在滚动 tableview 时却不再工作了?

如果我每次都创建了一个新的 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;
}

非常感谢!!

最佳答案

此行将一个 autoreleased 实例分配给 cellNib:

cellNib = [UINib nibWithNibName:@"NTDCell" bundle:nil];

这意味着使用以下行:

NSArray *nibArray = [cellNib instantiateWithOwner:self options:nil];

... cellNib 在关联的自动释放池被耗尽时已经被释放,使用它会导致未定义的行为。

如果您希望 cellNib 保留它的所有权,例如通过使用声明的属性:

self.cellNib = [UINib nibWithNibName:@"NTDCell" bundle:nil];

关于iphone - 使用 UINib/指针擅离职守的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3734157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com