【问题标题】:Class Extension - unrecognized setter类扩展 - 无法识别的设置器
【发布时间】:2012-08-18 01:49:01
【问题描述】:

以下代码崩溃:

@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

【问题讨论】:

    标签: iphone objective-c ios xcode ipad


    【解决方案1】:

    类扩展主要用于增强公共属性变量。假设你暴露了 readonly 对象,或者任何变量的 getter 方法,那么你在 extension 中创建了与 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
    

    【讨论】:

      【解决方案2】:

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

      这是正确的做法:

      @interface AppDelegate ()
      
      @property (nonatomic, strong) NSString * name;
      
      @end
      

      【讨论】:

      • 谢谢,通常我会使用category来实现私有方法(在.h中不可见),那么现在我可以将私有方法放在extension而不是category中吗?这是一种常见的做法吗?例如@interface AppDelegate () - (void) 开始; \@property (nonatomic, strong) NSString * name; \@结束
      • 是的,您可以将方法放在类扩展中。但是,我认为在 Xcode 4.4 下,您不再需要声明私有方法。
      • 谢谢!!! 1. 那么使用category声明私有方法和使用extension有什么区别呢?过去我看到很多人为此目的使用类别.. 2. 是的,Xcode 4.4 中不需要,但我只是想摆脱警告..
      • 谢谢..但似乎很多人更喜欢使用类别来实现私有方法,比如谷歌:code.google.com/p/gdata-objectivec-client/source/browse/trunk/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多