I thought that I knew how to use fast enumeration, but there is something I don\'t understand about it. If I create three NSString
objects and three NSNum
in fast enumeration no typecasting,just assigning the pointer into new object
When you write a forin loop like that, it casts every object in the array as an NSString, then prints them out as requested.
If you want only the NSStrings, you would need to write something like this:
for (id obj in array) {
if ([obj isKindOfClass:[NSString class]]) {
NSLog(@"str: %@", obj);
}
}
I don't understand where is the unexpected behavior, using the enhanced for loop in an NSMutableArray
will just iterate thru every single object in the array which in your case is 6, the result is correct and expected.
The numbers will just get casted to Strings.
I'm pretty sure that fast enumeration returns all objects in the array- all that you're doing in for (NSString *str in array)
is typecasting str
to an NSString
. In the body of the loop you need to check the class of the returned object to make sure that it is an NSString
.
for(NSString *str in array)
{
if([str isKindOfClass:[NSString class]])
NSLog(@"str : %@", str);
}
Every object that descends from NSObject implements the method - (NSString)description, %@ in Objective-C formate string will take the corresponding argument for the %@ and call its description method, Most subclasses of NSObject will implement there own version of - (NSString)description. The same thing happens when you type
> po anObject
in the debugger.
for (NSString *str in array) {
is a way to enumerate through all the elements in array.
You expectative that by specifying NSString
you get only the objects of that type is not correct. Rather, all the objects pointers are cast to that type (NSString*
).
Have a look at Fast Enumeration in The Objective-C Programming Language guide.