2

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

dpigera
  • 3,339
  • 5
  • 39
  • 60

3 Answers3

5

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];
sidyll
  • 57,726
  • 14
  • 108
  • 151
  • 1
    +1 for `/* This is not Python */`. I'd give another +1 for 'This is a terrible design', because it is. – Perception Jul 28 '11 at 18:03
  • 2
    -1 for 'This is a terrible design', because you don't have to be a douche. Something like "No, but if you could replace the collection of NSNumbers with a single NSArray of NSNumbers, you could loop through that by ...' would have got the point across without being offensive. – GeneralMike Nov 08 '12 at 20:50
2

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.

George Johnston
  • 31,652
  • 27
  • 127
  • 172
1

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

Community
  • 1
  • 1
roman
  • 11,143
  • 1
  • 31
  • 42