1

以下代码崩溃:

@interface AppDelegate (PrivateMethods)

@property (nonatomic, strong) NSString * name;

@end

@implementation AppDelegate

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    self.name = @"foobar";
    ...

错误是:

'-[AppDelegate setName:]: unrecognized selector sent to instance 0x6d73df0'

当我改变

@interface AppDelegate (PrivateMethods)

@interface AppDelegate ()

然后就好了,请问是什么原因呢?

更新:正如下面回答的那样,因为我必须为此目的使用类扩展,所以现在这个问题变成了:使用类扩展来声明私有方法是否可以接受?

例如

@interface AppDelegate ()

- (void) start;
@property (nonatomic, strong) NSString * name;

@end
4

2 回答 2

2

类扩展主要用于增强公共属性变量。假设你已经暴露了 readonly 对象,或者任何变量的 getter 方法,那么你在扩展中创建了与 readwrite 相同的对象。而 Category 仅用于增强类的方法/功能。

检查这个

@interface MyClass : NSObject
// property here is used as readonly.
@property (retain, readonly) float value;
@end

// Private extension, typically hidden in the main implementation file.
@interface MyClass ()
@property (retain, readwrite) float value;
@end

或者

@interface MyClass : NSObject
// here we have exposed getter method of private instance.
- (float) value;
@end

// Private extension, typically hidden in the main implementation file.
@interface MyClass ()
@property (retain, strong) float value;
@end
于 2012-08-17T17:36:42.830 回答
0

一个是类别,另一个是类扩展。如果要向现有类添加属性,则需要使用后者。

这是正确的做法:

@interface AppDelegate ()

@property (nonatomic, strong) NSString * name;

@end
于 2012-08-17T17:11:17.320 回答