简体   繁体   中英

Using NSArray for C-type int comparisons

I would like to iterate through an NSArray of ints and compare each one to a specific int. All ints are C type ints.

The code I am using is as follows:

-(int)ladderCalc: (NSArray*)amounts: (int)amount 
{
    int result;

    for (NSUInteger i=0; i< [amounts count]; i++) 
    {
        if (amount < [amounts objectAtIndex:i]);
        {
            // do something
        }
        // do something
    }
}

However I get an error when comparing the int amount to the result of [amounts objectAtIndex:i] because you cannot compare id to int. Why is the id involved in this case? Shouldn't objectAtIndex just return the object at the index specified? Is it possible to cast the object returned to an C int and then do the comparison?

Or should I just dispense with NSArray and do this type of thing in C?

You're missing a call to intValue in there (assuming that your array contains instances of NSNumber , which is fair to assume).

Also for sake of performance you'll probably want to call [amounts count] only once, like so:

-(int)ladderCalc:(NSArray *)amounts:(int)amount 
{
    int result;
    NSUInteger amountCount = [amounts count];
    for (NSUInteger i = 0; i < amountCount; i++) 
    {
        if (amount < [[amounts objectAtIndex:i] intValue]);
        {
            // do something
        }
        // do something
    }
}

And here's an even faster thanks to (system-optimized) fast enumeration:

-(int)ladderCalc:(NSArray *)amounts:(int)amount 
{
    int result;
    for (NSNumber *amount in amounts) {
        if (amount < [amount intValue]) {
            // do something
        }
        // do something
    }
}

And one that's even faster than the previous one, thanks to concurrent execution:

-(int)ladderCalc:(NSArray *)amounts:(int)amount 
{
    int result;
    [amounts enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *amount, NSUInteger idx, BOOL *stop) {
        if (amount < [amount intValue]) {
            // do something
        }
        // do something
    }];
}

Word of caution: The last version requires your // do something s to be NOT dependent on each other, due to concurrency.

NSArray is an array that contains objects, not primitive types. To put C integers into an array you typically wrap those in instances of the NSNumber class. The NSArray would then contain NSNumber objects, from which you can easily get the primitive values using the intValue method, as @Regexident demonstrates the other posted answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM