如何在iOS中的Objective-C中创建私有方法和ivars> = 4.0?

时间:2012-02-03 00:04:56

标签: objective-c ios

我听说最近可以通过在.m文件中再次声明接口来创建私有方法。但究竟是什么语法呢?

如果重要:在ARC下。

  • 必须在@implementation之前出现吗?
  • 它看起来与.h文件中的@interface声明完全相同吗?
  • 是否必须复制有关继承和协议合规性的信息?
  • 从什么时候开始?什么是支持它的最古老的iOS和Objc-C运行时?

1 个答案:

答案 0 :(得分:10)

标题文件:

//YourClass.h:
@interface YourClass {
    @private //optional
    //private scope ivars
    @protected //default, optional
    //protected scope ivars
    @public //optional
    //public scope ivars
    @package //optional
    //package scope ivars
}

    //public methods

@end

实施档案:

//YourClass.m:
#import "YourClass.h"

//you could also import this class extension (that's what it's called) from an
//external header file which can be helpful for making pseudo-protected methods/ivars
//Don't forget the additional import statement then, though.
@interface YourClass () <PrivateProtocol> //protocol tag optional, of cource

    @private //optional
    //private scope hidden ivars
    @protected //default, optional
    //protected scope hidden ivars
    @public //optional
    //public scope hidden ivars
    @package //optional
    //package scope hidden ivars

@end

@implementation YourClass

//your class' method implementations

@end
关于ivar范围的

Docs

有关上述代码段中的新功能及其相关内容(兼容性等)的详细信息,请参阅 WWDC 2011 Session #322

Xcode 4.2带来了隐藏的私人ivars。 类扩展已经存在了很长一段时间。