iphone - 类扩展 - 无法识别的二传手

标签 iphone objective-c ios xcode ipad

以下代码崩溃了:

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

相关文章:

iphone - 您如何在 Xcode 中检测 iOS 上的日期

ios - Apple Developer/iOS 分发证书管理

objective-c - 刷新 UIViewController 的界面方向

ios - [UINavigationController保留] : message sent to deallocated instance

objective-c - UITableViewCell 和 UITextField 的滚动问题

iphone - 旧的 Iphone sdk 版本

iphone - 如何在iOS中自定义搜索键盘?

objective-c - 如何删除有 0 个参与者的 Game Center 游戏

ios - Swift UIScrollView 在没有 pagingEnabled 的情况下捕捉到 subview 宽度

ios - NSCache 和持久性?