在Objective C中使用静态init时的好处?

Jos*_* B. 12 objective-c ios webrtc

最近我发现了来自Github的webrtc-ios示例.当我浏览项目时,我注意到VideoView类使用静态方法,我不确定是否有必要.VideoView是UIView的子类,它覆盖了两个init方法,initWithFrame:initWithCoder:.我知道覆盖这些init方法然后使用一些方法来设置其他东西是很正常的- (void)setup;.

但是VideoView类使用静态函数static void init(VideoView *self).问题是使用静态函数与普通ObjC方法有什么好处?

VideoView类中的代码如下所示:

-(id)initWithFrame:(CGRect)frame {

     if (self = [super initWithFrame:frame]) {
         init(self);
     }
     return self; 
}

-(id)initWithCoder:(NSCoder *)aDecoder {

     if (self = [super initWithCoder:aDecoder]) {
         init(self);
     }
     return self; 
}

 static void init(VideoView *self) { ... }
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 15

使用静态函数和Objective-C方法之间的一个区别是静态函数不能在子类中重写.如果公共init代码是在a中完成的

- (void)setup;
Run Code Online (Sandbox Code Playgroud)

方法和子类MyVideoViewVideoView情况来实现具有相同名称的方法,然后

[[MyVideoView alloc] initWithFrame:..]
Run Code Online (Sandbox Code Playgroud)

将调用可能不需要的子类实现.

在您的代码中, initWithFrame/ initWithCoder将始终调用本地init()函数,即使初始化子类的实例也是如此.

如果方法中完成公共初始化,那么方法名称应该更具体,以避免它被"意外"覆盖,例如

-(void)commonVideoViewSetup;
Run Code Online (Sandbox Code Playgroud)