【问题标题】:[NSCFNumber isEqualToString:]: unrecognized selector sent to instance[NSCFNumber isEqualToString:]:无法识别的选择器发送到实例
【发布时间】:2011-10-16 03:01:24
【问题描述】:

好的,我遇到了以下常见问题

[NSCFNumber isEqualToString:]: unrecognized selector sent to instance

但这次我不知道如何解决它。

这是viewDidLoad:中的声明

- (void)viewDidLoad {

    [super viewDidLoad];

    NSMutableArray *tempHours = [NSMutableArray array];
    for (int i = 0; i < 12; i++) { 
        [tempHours addObject:[NSNumber numberWithInt:(i+1)]];
    }
    self.hours = tempHours; // 'hours' is a synthesized NSArray property of the ViewController
    [tempHours release];

  // two more similar array declarations here

}

这是 UIPickerView 的代码方法,其中的东西会中断(例如,if 语句)

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

    NSString *stringIndex = [NSString stringWithFormat:@"Row #%d", row];

    if(component == 0) {
        return stringIndex = [self.hours objectAtIndex:row];
    }

    // more code for other components (of the same form) here

    return stringIndex;
}

我想我需要将我的 NSNumber 对象的 NSArray 类型转换为字符串。我该如何正确地使用该语句:

stringIndex = [self.hours objectAtIndex:row];

谢谢!

【问题讨论】:

  • 注:你不应该在viewDidLoad 中释放tempHours。您不拥有它,因为您没有创建它。

标签: objective-c ios nsstring int


【解决方案1】:
return [NSString stringWithFormat:@"%@",[self.hours objectAtIndex:row]];

【讨论】:

【解决方案2】:

您将返回一个NSNumber,因为这是self.hours 中的内容。由于NSString 是预期的返回值,您应该通过以下方式创建一个字符串:

[NSString stringWithFormat:@"%@", [self.hours objectAtIndex:row]];

或重新评估您的意图。您是真的想以这种方式存储索引,还是想存储NSStrings

【讨论】:

  • 我想存储数小时的数字。几分钟,我需要存储字符串,因为我在数字 1-9 前面加上 0。当我应用didSelect: 方法时,我必须稍后将这些值读回数字
【解决方案3】:

如果有人遇到此问题并专门返回行的索引,那么您始终可以通过执行以下操作将 NSNumber 转换为 stringValue:

NSString *code = [[[JSONResponse objectForKey:@"meta"] objectForKey:@"code"] stringValue];

在方法末尾放置stringValue 会将任何内容转换为字符串,您也可以使用intValue

【讨论】:

    【解决方案4】:

    评论[tempHours release];//它是自动释放的对象。您没有将 and 与 alloc 或 copy 或 new 一起使用:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        NSMutableArray *tempHours = [NSMutableArray array];
    
        for (int i = 0; i < 12; i++) { 
            [tempHours addObject:[NSNumber numberWithInt:(i+1)]];
        }
    
        self.hours = tempHours; // 'hours' is a synthesized NSArray property of the ViewController
    
        // [tempHours release];
    }
    

    你已经将 NSNumber 添加到数组中 所以 转换为字符串值:

    stringIndex =[NSString stringWithFormat:@"%@",[self.hours objectAtIndex:row]];
    

    【讨论】:

    • 不,这仍然行不通。抛出此错误-[NSCFString stringValue]: unrecognized selector sent to instance
    • 所以你已经在小时数组中添加了一些字符串。所以像上面的 stringwithformat 一样使用
    • 是的,我也很感激!谢谢!
    猜你喜欢
    • 2013-01-17
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2012-07-24
    相关资源
    最近更新 更多