tags:

views:

234

answers:

2

I'm using the following code to add a displayValue method to NSObject:

@interface NSObject (MyNSObjectAdditions)
- (NSString*)displayValue;
@end


@implementation NSObject (MyNSObjectAdditions)
- (NSString*)displayValue {
    return self.description;
}
@end

This works great, but really I'd rather have displayValue be a read-only property instead of a method.

What would be the proper syntax to convert displayValue to be a property instead of a selector, if it's even possible?

+1  A: 

Looks like your -displayValue method doesn't add anything to -description. Why do you want to do this?

NSResponder
By default -displayValue returns -description, but doing this allows me to subclass -displayValue in other objects on a case-by-case basis.
Mike
Why don't you just override -description on a case-by-case basis?
bobDevil
Because overriding description has far reaching effects. Other parts of the code may rely on descriptions being output in a particular way and I don't want to change that. Besides, conceptually I'm not really changing what an object should "look like", just how it should be rendered in this particular module (which outputs html in this example).
Mike
+4  A: 

You can only add new methods to a class using categories. If you really want to add new instance variables, you will have to subclass NSObject.

In any case, adding functionalities to NSObject is rarely a good idea. Can you explain what you are trying to achieve?

Martin Cote
I have to disagree with you. I've added categories to NSObject plenty of times. It's a perfectly valid option for adding behavior to pretty much everything in your class tree at once. You just need to take care not to clobber any existing methods.
NSResponder