开发者

If the type of objects in a collection is known, should I specify the type of the iterating variable when using fast enumeration?

开发者 https://www.devze.com 2023-02-06 09:09 出处:网络
For example, say I have an NSArray that contains a bunch of NSString objects: NSArray *games = [NSArray arrayWithObjects:@\"Space Invaders\", @\"Dig Dug\", @\"Galaga\", nil];

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开发者_如何学Python]);
    // Do some other stuff...
}


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 (an NSString method) on every object. In order to avoid compiler warnings, you'd cast the object to the specific type - which is what NSFastEnumeration does for you when you specify a non-id type. So yeah, use your second example.


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

0

精彩评论

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