【问题标题】:Convert id type to int [duplicate]将id类型转换为int [重复]
【发布时间】:2014-03-08 21:03:47
【问题描述】:

我想这真的很简单,但我找不到解决这个问题的方法......

@property (strong, nonatomic) NSMutableArray *randomQuestionNumberArray;

我有一个像这样开头的方法

- (int)showQuestionMethod:(int)number;

在这种方法中,我有一个循环,我用数字填充NSMutableArray,然后随机播放。

//Creating random questions array
_randomQuestionNumberArray = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfQuestions; i++) {
    [_randomQuestionNumberArray addObject:[NSNumber numberWithInt:i]];
}

//Shuffling the array
NSUInteger count = [_randomQuestionNumberArray count];
for (NSUInteger i = 0; i < count; ++i) {
    // Select a random element between i and end of array to swap with.
    int nElements = count - i;
    int n = (arc4random() % nElements) + i;
    [_randomQuestionNumberArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

这很好用。假设它会随机播放 4、5、1、3、6、0、2 等数字。

现在在 viewDidLoad 中,我尝试使用第一个值 _randomQuestionNumberArray 调用方法 showQuestionMethod,在这种情况下应该是 4。

[self showQuestionMethod:[_randomQuestionNumberArray[0] intValue]];

问题是该方法一直传递 0 的值,而它应该是 4,但 NSLog(@"first value is %@", _randomQuestionNumberArray[0]) 返回正确的值 4。

如何解决这个问题并将 id 类型转换为 int?

【问题讨论】:

  • NSLog(@"first value is %i", [_randomQuestionNumberArray[0] intValue]); 显示了什么?
  • 它应该显示为 4,但我在调用方法时仍然无法传递此值
  • 请勿转发您的问题。

标签: ios objective-c


【解决方案1】:

你可以试试这个:

[self showQuestionMethod:[(NSNumber)_randomQuestionNumberArray[0] intValue]];

【讨论】:

  • 这完全等同于现有的代码(假设你把不正确的(NSNumber)改成(NSNumber *));它不会解决问题。
  • 使用类型 'NSNumber' 需要算术或指针类型
  • 是的,你是对的,* 丢失了,它没有任何区别——我已经发布了一个新的答案。代码示例对于评论来说太大了。
【解决方案2】:

您确定传递了错误的值吗?也许您的 showQuestionMethod 中的 NSLog 语句有问题。

我试过这段代码,它工作正常:

    - (IBAction)start:(id)sender {
NSMutableArray *_randomQuestionNumberArray;
int numberOfQuestions=5;


_randomQuestionNumberArray = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfQuestions; i++) {
    [_randomQuestionNumberArray addObject:[NSNumber numberWithInt:i]];
}

//shuffling the array
NSUInteger count = [_randomQuestionNumberArray count];
for (NSUInteger i = 0; i < count; ++i) {
    // Select a random element between i and end of array to swap with.
    int nElements = count - i;
    int n = (arc4random() % nElements) + i;
    [_randomQuestionNumberArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}
NSLog(@"first value is %@", _randomQuestionNumberArray[0]);
[self showQuestionMethod:[_randomQuestionNumberArray[0] intValue]];  

}

- (void)showQuestionMethod:(int)number {
NSLog(@"number is %d", number);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    相关资源
    最近更新 更多