0

The code below produces and error in the line [myArray objectAtIndex:i]; and I can't seem to figure out why?

Any ideas?

int total = 0;
    for (int i = 0; i < myArray.count; i++) {
        int tempNumber = [myArray objectAtIndex:i];
        total = total + tempNumber;
    }

2 Answers 2

6

It could be because you are setting an object to an int. By definition, objectAtIndex returns an object.

Depending on the type of object in myArray, you can try something like this:

int tempNumber = [[myArray objectAtIndex:i] intValue];
Sign up to request clarification or add additional context in comments.

Comments

2

If you didn't put ints into your array, then you need to do something extra to get ints out. If you're getting an error with your code above, then it's because you don't have ints in the array, and you need

int myInteger = [[myArray objectAtIndex:i] intValue];

Or something to get the ints out of the array, depending on the rest of your code.

2 Comments

But they are not required to. Using some CoreFoundation magic, you can actually store primitives inside a NSArray.
@RichardJ.RossIII - That sounds cool; how would one go about doing that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.