开发者

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

开发者 https://www.devze.com 2023-01-31 14:10 出处:网络
Just like back in the pre-generics Java days, I write code like this: UIView *ball = [self.balls objectAtIndex:i];

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.b开发者_如何学Calls 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号