emmby
emmby

Reputation: 100464

How to add a property to NSObject in Objective-C?

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?

Upvotes: 3

Views: 5225

Answers (3)

Clay Bridges
Clay Bridges

Reputation: 11880

You can have properties in categories. In categories that are not class extensions (AKA class continuations), you can't use @synthesize. However, it's simple to write backing methods instead. In your case, this works:

@interface NSObject (MyNSObjectAdditions)
@property (readonly) NSString *displayValue;
@end

@implementation NSObject (MyNSObjectAdditions)

- (NSString *)displayValue {
    return self.description;
}

@end

Upvotes: 3

Martin Cote
Martin Cote

Reputation: 29842

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?

Upvotes: 3

NSResponder
NSResponder

Reputation: 16861

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

Upvotes: 1

Related Questions