Fast enumeration on NSArray of different types

I have this question here (as well as other SO questions), as well as Apple docs on Objective-C collections and a quick listing. Which is not clear if it is NSArrayfilled with different types, and the loop is created as:

for ( NSString *string in myArray )
    NSLog( @"%@\n", string );

What exactly is going on here? Will a loop skip everything that isn't NSString? For example, if (for an argument) a UIViewis in an array, what happens when the loop encounters this element?

+5
source share
5 answers

? , . , :

for (id object in myArray) {
    // Check what kind of class it is
    if ([object isKindOfClass:[UIView class]]) {
       // Do something
    }
    else {
       // Handle accordingly
    }
}

, , , ,

for (id object in myArray) {
    NSString *string = (NSString *)object;
    NSLog(@"%@\n", string);
}

, object, (NSString *) , string NSString. NSLog() - (NSString *)description

+9

, obj-c . NSString*, . id.

Obj-c runtime , . NSNumbers NSString . ( ), .

? , :


for (NSUInteger i = 0; i < myArray.count; i++) {
    NSString* string = [myArray objectAtIndex:i];

    [...]
}

, .

+3

. -

for ( NSObject *obj in myArray )
    NSLog( @"%@\n", obj );

, ,

for ( NSString *string in myArray )
    NSLog( @"%@\n", string );

NSString. , ,

for ( NSObject *obj in myArray ) {
    NSString *string = obj;
    NSLog( @"%@\n", string );
}

Apple , , .

+2

... .

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1];
NSNumber *number = [NSNumber numberWithInteger:6];
[array addObject:number];
[array addObject:@"Second"];

, , . NSNumber NSString, -description, .

for (NSString *string in array)
{
    NSLog(@"%@", string);
}

, -length NSString...

for (NSString *string in array)
{
    NSLog(@"%i", string.length);
}

... NSInvalidArgumentException, NSNumber -length. , Objective-C . .

+2

NSObject isKindOfClass, :

for(NSString *string in myArray) {
    if (![string isKindOfClass:[NSString class]])
        continue;
    // proceed, knowing you have a valid NSString *
    // ...
}
+1

All Articles