views:

86

answers:

2

I have a brand new Objective-C class called test. The test class has an instance variable called someValue, which contains an integer.

I create 5 instances of the test class called aTest, bTest, cTest, dTest and eTest. The appropriate synthesize and property declarations for someValue are in place.

Is there a clean way of returning the name of the class instance with the highest someValue value out of all the existing test class instances? The number of class instances may vary from the 5 in my example.

Note I don't care what the value is, I just want to return the name of the class instance with the highest 'someValue' instance variable.

I've tried a few NSMutable arrays however can only get the value not the name of the variable that contains it.

Thanks in advance

A: 

Assuming your object has a class name of "YourObject":

NSArray *objects = [NSArray arrayWithObjects:aTest, bTest, cTest, dTest, eTest, nil];
int i = [objects count];
int max = 0;
YourObject *highest;
while (i--)
{
    int current = ((YourObject *)[objects objectAtIndex:i]).someValue;
    if (current > max)
    {
        max = current;
        highest = (YourObject *)[objects objectAtIndex:i];
    }
}

// highest will be reference to object with highest someValue
NSLog(@"%@", highest);
Typeoneerror
Typeoneerror that looks pretty much perfect, I'm just getting a 'NSArray may not respond to -length' error which means the loop doesn't know how many times to repeat
Timbo
@Timbo: The selctor for the number of items in an array is `count` not `length`. There's always a chance of a typo in an example like this, but it should have been pretty obvious what the intent was and you could then have checked the NSArray class reference to find the correct selector.
JeremyP
Ok cool I'm new to this, thanks all for your patience :)
Timbo
Oops sorry, count!, yes. Editing. Was doing Actionscript all day and mixed my arrays up. ;)
Typeoneerror
Ok I've used count and that's exactly what I want thanks Typeoneerror :)
Timbo
+3  A: 

If I'm reading your question correctly, you've defined a bunch of variables (aTest, bTest, cTest, dTest and eTest) to be instances of your test class.

test *aTest = [[test alloc] initWithSomeValue:5];
test *bTest = [[test alloc] initWithSomeValue:42];
/* ... and so on ... */

Variable names are meaningless to the computer. All the compiler cares about is that each one is (potentially) unique. Once the code is compiled, all the variable names are completely stripped out; all that's left are numbers representing the memory locations of each.

You only use named variables as a way to write your code in a human-readable manner. If you wish to associate a string with each instance of your test class, you need to explicitly do so with a NSString instance member. You would then write:

test *aTest = [[test alloc] initWithSomeValue:5];
[aTest setName:@"a"];
test *bTest = [[test alloc] initWithSomeValue:42];
[bTest setName:@"b"];
Matt B.