(1)不少从其余语言(例如C++)转到objective c的初学者,每每会问到一个问题,如何定义类的私有函数?这里的“私有函数”指的是,某个函数只能在类的内部使用,不能在类的外部,或者派生类内部使用。事实上,Objective C中能够定义类的私有变量,但因为objective c是动态语言,所以本质上是不存在私有函数的。可是,也能够用一些机制,来实现相似其余语言中私有函数的效果。objective-c
(2)通常来讲,可使用两种方式来实现。函数
第一种:只在.m文件中实现该函数,不在.h文件中声明,这样是最简单的方式。spa
.h文件 @interfaceMyClass { // My Instance Variables } - (void)myPublicMethod; @end .m 文件: @implementationMyClass - (void)myPublicMethod { // Implementation goes here } - (void)myPrivateMethod { // Implementation goes here } @end
上面的myPrivateMethod函数只在m文件中实现了,没有在h文件中声明,那么外部就不能使用:[obj myPrivateMethod]的方式调用,在派生类中也不能使用[super myPrivateMethod] 或者[self myPrivateMethod]的方式来调用。code
第二种:在m文件中加上一个oc extension,在里面声明须要的私有函数。orm
.h 文件: @interfaceMyClass { // My Instance Variables } - (void)myPublicMethod; @end .m 文件: @interfaceMyClass() - (void)myPrivateMethod; @end @implementationMyClass - (void)myPublicMethod { // Implementation goes here } - (void)myPrivateMethod { // Implementation goes here } @end
以上两种方式,功能彻底同样,区别仅仅在于,团队开发时,后面一种的代码可读性更好,因此通常仍是推荐后面一种方式。blog
(3)前面已经提到,对于Objective C来讲,真正意义上的私有函数是不存在的。由于即便用上述的方法,不在头文件中声明函数,外部也可使用objc_msgSend或者performSelector来调用这个函数。 好比上面的myPrivateMethod,在类的外部能够直接使用[obj performSelector:@selector(myPrivateMethod)]… 来调用。有人说performSelector只能传一个参数,那么使用objc_msgSend(obj, @selector, …),就能够传N个参数了。因此说,用上面的机制,能够实现相似其余语言中“私有函数”的效果,但并不能彻底保证这个函数是私有的。开发
备注:在下面附上的帖子里有人提到,能够用一个外部的block来实现私有函数,可是这其实意义不大,由于在外部的block里面是不能访问类的self的,已经不算是成员函数了。it
参考:http://stackoverflow.com/questions/647079/is-it-possible-to-declare-a-method-as-private-in-objective-cio
http://stackoverflow.com/questions/172598/best-way-to-define-private-methods-for-a-class-in-objective-c/651852#651852form