如何在Objective-C中向NSObject添加属性?

时间:2022-09-07 10:14:58

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

我正在使用以下代码向NSObject添加displayValue方法:

@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.

这很好,但是我希望displayValue是只读属性,而不是方法。

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

如果可能的话,将displayValue转换成属性而不是选择器的正确语法是什么?

3 个解决方案

#1


4  

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.

只能使用类别向类添加新方法。如果您真的想添加新的实例变量,您将不得不子类化NSObject。

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

无论如何,向NSObject添加功能很少是一个好主意。你能解释一下你想要达到的目标吗?

#2


3  

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:

在类别中可以有属性。在非类扩展(也称为类延续)的类别中,不能使用@synthesize。然而,相反,编写备份方法很简单。就你的情况而言,这行得通:

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

@implementation NSObject (MyNSObjectAdditions)

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

@end

#3


2  

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

看起来你的-displayValue方法没有向-description添加任何东西。你为什么要这么做?

#1


4  

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.

只能使用类别向类添加新方法。如果您真的想添加新的实例变量,您将不得不子类化NSObject。

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

无论如何,向NSObject添加功能很少是一个好主意。你能解释一下你想要达到的目标吗?

#2


3  

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:

在类别中可以有属性。在非类扩展(也称为类延续)的类别中,不能使用@synthesize。然而,相反,编写备份方法很简单。就你的情况而言,这行得通:

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

@implementation NSObject (MyNSObjectAdditions)

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

@end

#3


2  

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

看起来你的-displayValue方法没有向-description添加任何东西。你为什么要这么做?