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

I use the following code to add a method displayValueto NSObject:

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


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

This works fine, but in fact, I would prefer displayValue to be a read-only property rather than a method.

What would be the correct syntax for converting displayValueas a property instead of a selector, if possible?

+3
source share
3 answers

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 functions to NSObject is rarely a good idea. Can you explain what you are trying to achieve?

+4

. , ( AKA), @synthesize. . :

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

@implementation NSObject (MyNSObjectAdditions)

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

@end
+3

It looks like your -displayValue method does not add anything to -description. Why would you want to do that?

+2
source

Source: https://habr.com/ru/post/1732428/


All Articles