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

前端 未结 2 1547
庸人自扰
庸人自扰 2020-12-20 14:54

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 th

相关标签:
2条回答
  • 2020-12-20 15:41

    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));
    }
    
    0 讨论(0)
  • 2020-12-20 15:52

    You are using an int where an object (presumably NSNumber) is expected. So convert before use:

    if ([drawnNumbers containsObject:@( drawnNumber )])
    
    0 讨论(0)
提交回复
热议问题