开发者

How do you enumerate through an array in Obj-C?

I have an array which has several objects (all of different classes) in it. But using enumeration doesn't work on it for some reason.

    NSString *arrayString;
    NSURL *arr开发者_StackOverflow中文版ayUrl;
    NSProcessInfo *arrayPr;
    NSDictionary *arrayDictionary;
    NSMutableString *arrayMString;

    NSMutableArray *objectArray = [NSMutableArray arrayWithObjects:arrayString,arrayUrl,arrayPr,arrayDictionary,arrayMString,nil];

    for( NSString *item in objectArray ){
        NSLog(@"Class name is: %@", [item className]);
    }

I think it might be something to do with how the objects are been added to the array but i'm new to objective-c and not sure.


you aren't actually populating the array.

NSString *arrayString;

declares a variable, arrayString, of type NSString. it's not initialized (so it deserves to crash when you use the variable -- but may be 0 with some build settings).

so, to assign a variable:

NSString *arrayString = [NSString stringWithFormat:@"sksjdhf %f\n", 3.3];

arrayWithObjects adds objects from the (va list) argument until nil/null/0 is encountered.

you must set up the remainder of your variables/arguments correctly before using them.

this should work as you expect it to:

NSString * str = @"a string";
NSMutableArray *objectArray = [NSMutableArray arrayWithObjects:str, nil];

for (NSObject * item in objectArray) {
    NSLog(@"Class name is: %@", [item className]);
}


In the for loop, use an id data type. The id data type is a general purpose data type that can be used to store a reference to any object.

For example:

    for ( id item in objectArray ) {
          NSLog(@"Class name is: %@", [item className]);
    }


Yep, that's how you do it. If you're having trouble, it is not in the enumeration syntax itself.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜