dpigera
dpigera

Reputation: 3369

iPhone : is there a way to loop through the attributes of an NSObject?

I have an NSObject defined as followed:

@interface MFMoodMix : NSObject {
    NSNumber *m1;
    NSNumber *m2;
    NSNumber *m3;
    NSNumber *m4;
    NSNumber *m5;
    NSNumber *m6;
    NSNumber *m7;
}

Is there any way I can loop through all these values quickly to find the largest one? e.g. like a UIView as for (UIView *x in view.subviews), is there a similar method to do this quickly?

Thanks

Upvotes: 2

Views: 826

Answers (3)

roman
roman

Reputation: 11278

if you somehow can't convert your numbers to an array, you could always do it the hard way and use the objc runtime :-)

there is a great thread about it here on so: Objective C Introspection/Reflection

Upvotes: 1

sidyll
sidyll

Reputation: 59327

No. This is a terrible design. Use an array of NSNumbers instead.

@interface MFMoodMix : NSObject {
    NSArray *ms;
}

And then in your init method (or somewhere else) add the numbers to the array:

-(id) init
{
    /* ... */
    ms = [[NSArray alloc] initWithObjects:
             [NSNumber ...],
             [NSNumber ...], nil];
    /* ... */
}

To iterate, just an example considering the NSNumber(s) are int(s):

int high = 0; /* or a negative number... */
/* This is not Python */
for (NSNumber *n in ms)
    if ([n intValue] > high)
        high = [n intValue];

Upvotes: 5

George Johnston
George Johnston

Reputation: 32278

If you have a collection of similar values that you need to access in the same manner, I would recommend simply placing them into a... collection. If you place these values into a NSArray, you can easily iterate through them and sort them any which way you'd like. If you want to maintain the m* prefix, you could substitute a NSDictionary and use the m values as your keys.

Upvotes: 2

Related Questions