以下代码崩溃了:
@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 ()
然后没关系,原因是什么?
更新:如下所述,由于我必须为此目的使用类扩展,现在这个问题变成:使用类扩展来声明私有方法是否可接受?
e.g。
@interface AppDelegate ()
- (void) start;
@property (nonatomic, strong) NSString * name;
@end
答案 0 :(得分: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
答案 1 :(得分:0)
一个是类别,另一个是类扩展。如果要向现有类添加属性,则需要使用后者。
这是正确的方法:
@interface AppDelegate ()
@property (nonatomic, strong) NSString * name;
@end