0

So I have an array with some objects (NSString, NSNumber, etc.) and I want to loop through it using a for loop. I thought I'd use the id for the type.

NSArray *myArray = [[NSArray alloc] initWithObjects:@"one string",@"another", @3, nil];
for (id *something in myArray) {
....
}

What's wrong with the for loop above? Why can't I use id and what would be the appropriate "type" to use.

I am a begginer in iOS dev.

2 Answers 2

4

id is intrinsically a pointer, hence all you need is:

for(id something in myArray) {

btw, using the constant object syntax makes such code more legible:

@[ @"one string", @"another", @3 ]
Sign up to request clarification or add additional context in comments.

5 Comments

I had tried that but it game a warning saying "Format string is not a string literal (potentially insecure)." Should I worry?
@espitia: That warning wouldn't be caused by the code you've shown us in your question. Try posting a new question for your new question.
None of the code here should give you that warning, perhaps you can post the rest of the for-loop? I'm guessing you use something as a format argument to NSLog?
The format string item you're seeing is due to code you haven't displayed... it's something like NSLog(someNsString)... in which case you should instead NSLog(@"%@", someNsString);. The issue is one of safety, assuming you would notice if a string literal had incorrect % flags, but you wouldn't notice if an NSString had them (and having them can cause code to, for example, crash).
ahhh yes! I was using NSLog(something). Thank you very much @mah and @david
2

id as a type already is a pointer, so id * is a pointer to a pointer, which is incorrect here. Try this:

for (id something in myArray) {

}

Comments

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.