1

这就是我在我的一个类的实现文件中的内容......

代码设置 #1

@interface MyViewController (PrivateMethods)
- (NSString *)myPrivateMethod;
@end

@implementation MyViewController
- (void)viewDidLoad
{
    NSString *myString = [self myPrivateMethod];
    NSLog(@"%@", myString);
}

- (NSString *)myPrivateMethod
{
    return @"someString";
}
@end

使用此代码,一切正常,并记录“someString”。

但是我的代码不应该以某种方式看起来不同吗?我实际上是偶然使用该类别的(我复制/粘贴了一些东西,但没有注意到“PrivateMethods”在那里;我的意思是使用类扩展)。

我的代码不应该看起来像以下之一:

代码设置 #2

@interface MyViewController ()
- (NSString *)myPrivateMethod;
@end

@implementation MyViewController
....

或者:

代码设置#3

@interface MyViewController (PrivateMethods)
- (NSString *)myPrivateMethod;
@end

@implementation MyViewController (PrivateMethods)
....

在这种情况下发生的事情背后的细微差别是什么?代码设置 #1 与代码设置 #2 有何不同?

编辑:关于设置 #3 的问题

像这样设置它会完成什么?这甚至会“工作”吗?

@interface MyViewController (PrivateMethods)
- (NSString *)myPrivateMethod;
@end

@implementation MyViewController
- (void)viewDidLoad
{
    NSString *myString = [self myPrivateMethod];
    NSLog(@"%@", myString);
}
@end

@implementation MyViewController (PrivateMethods)
- (NSString *)myPrivateMethod
{
    return @"someString";
}
@end
4

1 回答 1

2

选择器只是在运行时被推入同一个平面命名空间。编译器没有添加额外的代码来区分选择器是在类别中定义的方法(当消息传递时)——它都是平面的。

类别的符号以不同的方式导出,但这对于加载后的运行时并不重要。

您通常应该使用设置 #3:如果在类别中声明了方法,则应在类别的@implementation. 编译器偶尔会救你,它是一个更纯粹的结构。(当然,不是每个方法都属于一个类别)。类似地,在@interface对应的声明中应该定义@implementation,并且类延续(@interface MONClass ())中声明的定义也应该出现在primary中@implementation

@implementation MONClass
// add your @interface MONClass definitions here
// also add your @interface MONClass () definitions here
@end

更新的问题

是的,那会很好。您需要做#import的就是包含@interface MyViewController (PrivateMethods). 我实际上在某些课程中这样做是为了按主题分类/组织。

通常,“私有方法”在类延续中声明,但没有必要这样做(ivars/properties OTOH…)。

于 2012-09-20T18:42:22.193 回答