在目标 C 中进行比较 - ARC 不允许将“int"隐式

Comparing in objective C - Implicit conversion of #39;int#39; to #39;id#39; is disallowed with ARC(在目标 C 中进行比较 - ARC 不允许将“int隐式转换为“id)

本文介绍了在目标 C 中进行比较 - ARC 不允许将“int"隐式转换为“id"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在标有故障线"的行处收到错误ARC 不允许将 'int' 隐式转换为 'id'".我想这与我正在检查数组中的整数有关,该数组包含对象而不是整数.

I i'm getting the error "Implicit conversion of 'int' to 'id' is disallowed with ARC" at the line marked with "faulty line". I guess it have something to do with that i'm checking for an integer in an array, that contains objects instead of integers.

#import "RandomGenerator.h"

@implementation RandomGenerator

NSMutableArray *drawnNumbers;

-(int) randomNumber:(int)upperNumber {
    return arc4random_uniform(upperNumber);
}

-(NSMutableArray*) lotteryNumbers :(int)withMaximumDrawnNumbers :(int)andHighestNumber {
    for (int i = 1; i <= withMaximumDrawnNumbers; i++)
    {
        int drawnNumber = [self randomNumber:andHighestNumber];
        if ([drawnNumbers containsObject:drawnNumber]) {  //faulty line
            //foo
        }
    }
    return drawnNumbers;
}

@end

推荐答案

NSArrays 只能包含objective-c 对象.所以实际上 containsObject: 方法需要一个对象,而不是 int 或任何其他原始类型.

NSArrays can only contain objective-c objects. So actually the method containsObject: is expecting an object, not an int or any other primitive type.

如果你想在 NSArray 中存储数字,你应该将它们打包到 NSNumber 对象中.

If you want to store number inside an NSArray you should pack them into NSNumber objects.

NSNumber *someNumber = [NSNumber numberWithInt:3];

在您的情况下,如果我们假设 drawNumbers 已经是一个 NSNumbers 数组,您应该将 randomNumber: 代更改为:

In your case, if we assume that drawnNumbers is already an array of NSNumbers, you should change the randomNumber: generation to:

-(NSNumber*) randomNumber:(int)upperNumber {
    return [NSNumber numberWithInt:arc4random_uniform(upperNumber)];
}

然后在 lotteryNumbers 方法中选择它时,您应该:

And then when picking it up on the lotteryNumbers method, you should:

NSNumber *drawnNumber = [self randomNumber:andHighestNumber];

另一个注意事项是您为 lotteryNumbers 定义的方法.你用了一个很奇怪的名字,我想你误解了方法命名在objective-c中是如何工作的.您可能正在寻找类似的东西:

Another note would go for the method you defined for lotteryNumbers. You used a really strange name for it, I think you misunderstood how the method naming works in objective-c. You were probably looking for something more like:

-(NSMutableArray*) lotteryNumbersWithMaximumDrawnNumbers:(int)maximumDrawnNumbers andHighestNumber:(int)highestNumber;

后期

Objective-C 现在允许使用更紧凑的语法来创建 NSNumber.你可以这样做:

Objective-C now allows a way more compact syntax for creating NSNumbers. You can do it like:

NSNumber *someNumber = @(3);

你的方法可以改写为:

-(NSNumber*) randomNumber:(int)upperNumber {
    return @(arc4random_uniform(upperNumber));
}

这篇关于在目标 C 中进行比较 - ARC 不允许将“int"隐式转换为“id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在目标 C 中进行比较 - ARC 不允许将“int"隐式

基础教程推荐