Question

Here is an example of how the properties of a javascript object can be enumerated through. I noticed that the loop construct used was a for...in loop. Objective-C also has a for...in loop, so is the same behavior possible in Objective-C?

@interface Bar : NSObject
@property (nonatomic) NSString * stringA;
@property (nonatomic) NSString * stringB;
@property (nonatomic) NSString * stringC;
@end

int main(int argc, const char *argv[]) {
    Bar obj = [[Bar alloc] init];
    obj.stringA = @"1";
    obj.stringB = @"2";
    obj.stringC = @"3";

    for (NSString *property in obj) {
        NSLog(@"%@", property);
    }
}

Is this possible with Objective-C? If not, is there an alternative that would mimmic this behavior of iterating through an objects properties?

Was it helpful?

Solution 2

Fast enumeration

Bar *obj = [[Bar alloc] init];
// ...
for (id elem in obj) {
   ...
}

requires that the class Bar conforms to the NSFastEnumeration Protocol, i.e. it must implement the

countByEnumeratingWithState:objects:count:

method. (This is the case for all Objective-C collection classes such asNSArray, NSDictionary, NSSet.)

So the direct answer to your question is no, you cannot use the fast enumeration syntax for (... in ...) to enumerate all properties of an arbitrary class.

However, it is possible to implement the fast enumeration protocol for a custom class. Examples how this is done can be found here

OTHER TIPS

Short answer: yes it is possible.

Here's some sample code of what you're trying to achieve.

Header

@interface Bar : NSObject

@property (nonatomic, retain) NSString *stringA;
@property (nonatomic, retain) NSString *stringB;
@property (nonatomic, retain) NSString *stringC;

@end

Main

@implementation Bar
// don't forget to synthesize
@synthesize stringA, stringB, stringC;
@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        unsigned int numberOfProperties = 0;
        objc_property_t *propertyArray = class_copyPropertyList([Bar class], &numberOfProperties);

        for (NSUInteger i = 0; i < numberOfProperties; i++)
        {
            objc_property_t property = propertyArray[i];
            NSString *letter = [[NSString alloc] initWithUTF8String:property_getName(property)];
            NSString *attributesString = [[NSString alloc] initWithUTF8String:property_getAttributes(property)];
            NSLog(@"Property %@ attributes: %@", letter, attributesString);
        }
        free(propertyArray);
    }
}

Let me know if you have any questions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top