I have a brand new Objective-C class called test. The test class has an instance variable called someValue, which con开发者_如何学JAVAtains 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
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"];
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);
精彩评论