[英]array retain in table view objective c
我有点困惑。 当我在tableView dataSource方法numberOfRowsInSection中打印数组时,我的应用程序崩溃。
这是我的代码:.h文件中
@interface AddColor : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
UITableView *tblView;
NSArray *arrayColors;
}
@property(nonatomic,retain)NSArray *arrayColors;
@end
在.m文件中
@synthesize arrayColors;
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationController setNavigationBarHidden:NO];
arrayColors = [NSArray arrayWithObjects:@"blackColor", @"darkGrayColor", @"lightGrayColor", @"whiteColor", @"grayColor", @"redColor", @"greenColor", @"blueColor", @"cyanColor", @"yellowColor", @"magentaColor", @"orangeColor", @"purpleColor", @"brownColor", nil];
tblView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
tblView.delegate=self;
tblView.dataSource=self;
[self.view addSubview:tblView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(@"%d",[arrayColors count]);//App crashes here.
return [arrayColors count];
}
当我打印[arrayColors count]时,我的应用程序崩溃了;
我找到了崩溃的解决方案,我只是将数组保留在viewDidLoad中
[arrayColor retain];
现在工作正常。 但是为什么我的应用在打印[arrayColor count]之前崩溃了;
尝试使用[self.arrayColors count]-使用ivar getter和setter访问保留的属性
顺便说一句,我强烈建议您不要对表视图的大小进行硬编码。 至少要设置自动调整大小蒙版。
+ [NSArray arrayWithObjects:]
创建一个自动释放的数组-释放时未确定数组,但很可能在viewDidLoad
方法返回时释放了它,因此它是您在[arrayColor count]
访问的无效(垃圾)指针。
通过保留数组,可以消除释放错误,但是现在您正在泄漏内存。 解决此问题的正确方法的一般方法是使用初始化方法之一分配和初始化数组,例如
- (id)init
{
if ((self = [super init])) {
arrayColors = [[NSArray alloc] initWithObjects:..., nil];
}
return self;
}
然后将其清除- dealloc
,以免泄漏内存:
- (void)dealloc
{
[arrayColors release];
[super dealloc];
}
有关Apple Developer的更多信息。
您可能已经将DataSource和Delegate链接到了TableView而不是文件所有者。
如果你这样做
[self setArrayColors:[NSArray arrayWithObjects:@"blackColor", @"darkGrayColor", @"lightGrayColor", @"whiteColor", @"grayColor", @"redColor", @"greenColor", @"blueColor", @"cyanColor", @"yellowColor", @"magentaColor", @"orangeColor", @"purpleColor", @"brownColor", nil]];
它可以解决该问题而无需再次保留,但请确保在dealloc中释放它。
[arrayColors release];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.