Dan Rosenstark
Dan Rosenstark

Reputation: 69787

Using `id` To Get XCode to Stop Warning Instead of Correct Types

Just like back in the pre-generics Java days, I write code like this:

UIView *ball = [self.balls objectAtIndex:i];

which causes a compiler warning. I know that correct way to resolve it -- assuming it doesn't blow up at runtime -- is to use

UIView *ball = (UIView *)[self.balls objectAtIndex:i];

but recently I've been favoring

UIView *ball = (id)[self.balls objectAtIndex:i];

Is there ANY reason not to do this? Does it change anything at runtime? It's easier to type and read, I think.

Upvotes: 0

Views: 257

Answers (1)

Tommy
Tommy

Reputation: 100652

Either you've defined a custom type that responds to objectAtIndex: rather than using a built-in array or there is something wrong with your setup. NSArray's objectAtIndex: is defined to return type 'id', so casting the result to type 'id' has no effect. Furthermore, objects of any type can be assigned to id and objects of type id can be assigned to any other type without generating a compiler warning.

In any event, pointer casting has no effect at runtime. Objective-C does not modify the way that pointers work in C other than supplying a few additional implicit conversions.

Upvotes: 2

Related Questions