如果集合中对象的类型已知,那么在使用快速枚举时是否应该指定迭代变量的类型?
例如,假设我有一个包含一堆 NSString
对象的 NSArray
:
NSArray *games = [NSArray arrayWithObjects:@"Space Invaders", @"Dig Dug", @"Galaga", nil];
这样做的优点和缺点是什么:
for (id object in games) {
NSLog(@"The name of the game is: %@", object);
NSLog(@"The name is %d characters long.", [object length]);
// Do some other stuff...
}
与:
for (NSString *name in games) {
NSLog(@"The name of the game is: %@", name);
NSLog(@"The name is %d characters long.", [name length]);
// Do some other stuff...
}
For example, say I have an NSArray
that contains a bunch of NSString
objects:
NSArray *games = [NSArray arrayWithObjects:@"Space Invaders", @"Dig Dug", @"Galaga", nil];
What are the pros and cons of doing this:
for (id object in games) {
NSLog(@"The name of the game is: %@", object);
NSLog(@"The name is %d characters long.", [object length]);
// Do some other stuff...
}
versus:
for (NSString *name in games) {
NSLog(@"The name of the game is: %@", name);
NSLog(@"The name is %d characters long.", [name length]);
// Do some other stuff...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这并不是绝对必要的,并且会在每次迭代时强制转换为指定类型,因此除非您在循环内调用特定于
NSString
的方法,否则我不会不明白为什么这可能是有益的。所以,在你的情况下我会这样做,因为你在每个对象上调用
-length
(一个NSString
方法)。为了避免编译器警告,您可以将对象强制转换为特定类型 - 这就是当您指定非id
类型时NSFastEnumeration
为您所做的事情。所以是的,使用你的第二个例子。It's not strictly necessary, and will force a cast to the specified type on every iteration, so unless you are calling methods specific to
NSString
inside of your loop, then I don't see why this could be beneficial.So, in your case I would do it, because you're invoking
-length
(anNSString
method) on every object. In order to avoid compiler warnings, you'd cast the object to the specific type - which is whatNSFastEnumeration
does for you when you specify a non-id
type. So yeah, use your second example.如果您已经向迭代器传递了特定于类的消息,则无法通过将其类型指定为 id 来使其通用。如果您想让它“几乎”通用,您可以将层次结构中包含您计划使用的所有消息的最顶层类指定为迭代器类型。对于你的情况,这个类是 NSString
You can't make iterator universal by specifying it's type as
id
if you've already passed a class specific message to it. If you want to make it "almost" universal you can specify as iterator's type the top-most class in hierarchy having all messages you plan to use. For your case this class is NSString