以下代码崩溃了:
@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 ()
那么就可以了,请问是什么原因呢?
更新:如下所述,由于我必须为此目的使用类扩展,现在这个问题变成了:使用类扩展来声明私有(private)方法是否可以接受?
例如
@interface AppDelegate ()
- (void) start;
@property (nonatomic, strong) NSString * name;
@end
最佳答案
类扩展基本上用于增强公共(public)属性变量。假设你已经暴露了只读对象,或者任何变量的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
关于iphone - 类扩展 - 无法识别的二传手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12010118/