0

I have a class that has 4 integer properties. I have separate methods to compare one integer property to another instance. The comparison logic is the same for all integer properties. Is there a method or way I don't know how to one line selector different properties?

//Current sudo code compare

- (BOOL)compare1:otherInstance
{
    if (self.number1 == otherInstance.number2) return YES;
    else return NO;
}
- (BOOL)compare2:otherInstance
{
    if (self.number2 == otherInstance.number2) return YES;
    else return NO;
}

//Ideal way sudo code compare

- (BOOL)compare:otherInstance useProp:prop
{
    if ([self selectProp:prop] == [otherInstance selectProp:prop]) return YES;
    else return NO;
}

I can write my own little property select, but will prefer to use anything provided by objective c. The comparison is more complicated than the sudo code, just showing the part that for my question

owlaf
  • 1
  • 4
  • 1
    maybe the problem is on my side, but I have zero clue what you'd like to ask here... you may need to create a base class which implements the comparison method once, and you have to inherited the four integer(?) proeprties from that base class? I really tried to understand but I have no idea about your goal. – holex Jun 19 '14 at 15:21

1 Answers1

2

You can achieve that with Key-Value Coding:

-(BOOL)compare:(YourClass *)otherInstance useProp:(NSString *)prop
{
    NSNumber *val1 = [self valueForKey:prop];
    NSNumber *val2 = [otherInstance valueForKey:prop];
    return [val1 isEqual:val2];
}

Note that scalar properties are automatically wrapped into objects, therefore [self valueForKey:prop] returns an NSNumber if "prop" is an integer property. See "Scalar and Structure Support" in the "Key-Value Coding Programming Guide".

Note also that this will crash with a runtime exception if the property "prop" does not exist.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • you are so lucky if you understood the OP's question. :) – holex Jun 19 '14 at 15:22
  • Spot on Martin also made use of respondsToSelector:NSSelectorFromString found [here](http://stackoverflow.com/questions/1535190/in-objective-c-can-you-check-if-an-object-has-a-particular-property-or-message) to check if the property exists before attempting to use it. Many thanks – owlaf Jun 19 '14 at 19:47