我有一个导航视图iPhone应用程序。我创建了一个简单的对象,它有一个"名称"NSString和一个"权重"NSNumber。加载单元格时,此应用程序不断崩溃。这是方法:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
factor *toAdd = [factors objectAtIndex:indexPath.row];
cell.textLabel.text = toAdd.name;
cell.detailTextLabel.text = [toAdd.weight stringValue];
// ^ crashes here...
// stringByAppendingString:@"%"];
return cell;
}
在 NSNumber 上调用 stringValue 方法时,我在控制台上收到"发送到已解除分配的实例的消息"。我不明白为什么会这样。上面的行访问名称没有问题,我没有 [release] 语句。
谢谢
编辑:这是我因子的初始化方法。我仔细检查了一下,权重是(保留,非原子)并在实现中合成,就像名字一样。
- (id) init{
if( self = [super init] )
{
weight = [NSNumber numberWithInt:10];
name = @"Homework";
}
return self;
}
您没有在 init 中使用属性 setter 方法。因此,不会保留对象。
试试这个:
- (id) init{
if( self = [super init] )
{
self.weight = [NSNumber numberWithInt:10];
self.name = @"Homework";
}
return self;
}
若要避免这些类型的错误,可以使用以下命令合成属性:
@synthesize name = _name;
能够成功访问name
属性与weight
属性是否已释放无关。所有这一切都告诉你,你的factor
还活着,而且活得很好,它的name
也活得很好。我猜你在实施factor
时没有正确保留你的weight
属性。
编辑:使用添加的代码,这绝对是您正在做的事情。