for (i=0; i<10; i++) { [mas_m addObject:[NSDecimalNumber numberWithDouble:rand() % 2]]; } for (i_in in mas_m) { if (i_in==1) { NSLog(@"Yeah"); } } 

It gives an error ... what is the reason?

    1 answer 1

    NSDecimalNumber is not a number, but an object, and you can only compare it with the number of the first converted object. Further, when comparing NSDecimalNumber objects with == , not numbers are compared, but objects that contain these numbers, therefore, by comparing two different NSDecimalNumber objects, even if they contain the same number, you will get NO (false).

    Here is the correct entry:

     if ([i_in isEqualToNumber:@(1)])... 

    isEqualToNumber compares exactly the numbers that contain two corresponding instances of NSDecimalNumber.

    See, documentation / Cocoa / Reference / Foundation / Classes / NSNumber_Class / Reference / Reference.html # // apple_ref / occ / cl / NSNumber (first isEqualToNumber description :)

     NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic... 

    Accordingly, everything written here about NSDecimalNumber also holds in the case of its parent NSNumber.

    • Thank! I understand numbers should be added as [mas_m addObject: [NSNumber numberWithDouble: arc4random ()% 10]]; ? - Rosso777
    • Yes, you are doing everything right. - Stanislav Pankevich