Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ios - Comparing in objective C - Implicit conversion of 'int' to 'id' is disallowed with ARC

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

NSNumber *someNumber = [NSNumber numberWithInt:3];

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)];
}

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

NSNumber *drawnNumber = [self randomNumber:andHighestNumber];

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;

Late edit:

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

NSNumber *someNumber = @(3);

And your method could be rewritten as:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...