user1448650
user1448650

Reputation: 11

Objective-C generic getter methods

I need to overwrite the getter method of multiple properties using the getter attribute when I declare my property like the following. I would like the getter of all my properties to be the same method as the code to get those three properties is the same.

@property (nonatomic,strong, getter=getObject) (NSString*) obj1;
@property (nonatomic,strong, getter=getObject) (NSString*) obj2;
@property (nonatomic,strong, getter=getObject) (NSString*) obj3;

Although, I would need, in my getObject method, to know which property is currently being asked. Is is possible in the implementation of the getObject method to know which object is currently being asked? I would like the following %@ code to return either obj1, obj2 or obj3.

-(NSString*) getObject{ 

   NSLog(@"the property requested is: %@", ?????)

}

Any ideas on how to do that?

Thanks a lot! Renaud

Upvotes: 1

Views: 1188

Answers (1)

Mike Weller
Mike Weller

Reputation: 45598

This is not possible.

When you define your getter method, the compiler is going to translate requests to myObject.obj3 into simply [myObject getObject]. At that point, you have lost the information about which property was invoked.

You should just define a different getter for each property, and any shared or duplicated code can go into a private method like getObject::

- (NSString *)getObject:(NSString *)propertyName {
    // ...
}

- (NSString *)obj1 {
    return [self getObject:@"obj1"];
}

- (NSString *)obj2 {
    return [self getObject:@"obj2"];
}

// ...

Upvotes: 1

Related Questions