我的简单数组不起作用

时间:2011-04-19 20:50:17

标签: iphone objective-c

加载数组时应用程序正在冻结。

在NSString *权重行获取错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString stringValue]: unrecognized selector sent to instance 0x14904'

这是我的代码:

- (IBAction)weightButtonPressed
{
pickerArrayHalf = [[NSMutableArray alloc]initWithCapacity:2];
    [pickerArrayHalf addObject:@"0"];
    [pickerArrayHalf addObject:@"1/2"];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)];
    NSString *weight = [[pickerArrayHalf objectAtIndex:row] stringValue];
    label.text = [NSString stringWithFormat:@"%@", weight];
}

2 个答案:

答案 0 :(得分:3)

您使用NSString@"0"@"1/2"存储在数组中,NSString不响应stringValue,它是一个字符串。只需从方法调用中删除stringValue。

NSString *weight = [pickerArrayHalf objectAtIndex:row];

旁注:

您在设置标签文本时过于复杂。只需执行以下操作即可。

label.text = [pickerArrayHalf objectAtIndex:row];

此外,您不会重新调整该示例中应该生成警告的任何视图。最后一行应该是

//I would recommend calling autorelease on the initial alloc/initWithFrame
return [label autorelease];

答案 1 :(得分:0)

您正在向数组添加字符串:

[pickerArrayHalf addObject:@"0"];

因此以后没有必要在字符串中询问stringValue:

[[pickerArrayHalf objectAtIndex:row] stringValue];

摆脱对stringValue的调用(由于显而易见的原因,NSString甚至没有实现stringValue):

NSString *weight = [pickerArrayHalf objectAtIndex:row];

还有更多为什么要将字符串换成新字符串?:

label.text = [NSString stringWithFormat:@"%@", weight];

这样做:

NSString *weight = [pickerArrayHalf objectAtIndex:row];
label.text = weight;

甚至更短:

label.text = [pickerArrayHalf objectAtIndex:row];

最后但并非最不重要的是,pickerView :…方法正在泄漏label而未按预期返回UIView。