简体   繁体   中英

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?

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM