问题描述
最近我发现了。当我浏览项目时,我注意到VideoView类使用的是静态方法,我不确定是否有必要。
VideoView是UIView的子类,它覆盖了两个init方法, initWithFrame:
和 initWithCoder:
。我知道覆盖这些init方法然后使用一些方法设置其他东西是正常的,比如 - (void)setup;
。
Recently I've discovered webrtc-ios example from Github. While I was browsing though the project I noticed that VideoView class uses static method and I'm not sure is that necessary or not.VideoView is subclass of UIView and it overrides two init methods, initWithFrame:
and initWithCoder:
. I know it's normal to override those init methods and then use some method for setting up other stuff, like - (void)setup;
.
但VideoView类使用静态函数, static void init(VideoView * self)
。问题是使用静态函数与普通ObjC方法有什么好处?
But VideoView class uses static function, static void init(VideoView *self)
. Question is are there benefits when using static function vs. normal ObjC method?
VideoView类中的代码如下所示:
Code in VideoView class looks like this:
-(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) { ... }
推荐答案
使用静态函数和Objective-C方法的一个区别是
静态函数不能在子类中重写。如果公共初始化代码在
$ b
One difference between using a static function and an Objective-C method is thatthe static function cannot be overriden in a subclass. If the common init code is donein a
- (void)setup;
方法,以及 MyVideoView
的子类 VideoView
碰巧实现了一个同名的方法,然后
method, and a subclass MyVideoView
of VideoView
happens to implement a method with the same name, then
[[MyVideoView alloc] initWithFrame:..]
将调用可能不需要的子类实现。
will call the subclass implementation, which might not be wanted.
在你的代码中,
initWithFrame
/ initWithCoder
将始终调用本地 init()
函数,即使
初始化了子类的实例。
In your code,initWithFrame
/initWithCoder
will always call the local init()
function, even ifan instance of a subclass is initialized.
如果共同初始化是在方法中完成的,那么方法名称应该更具有
特定,以避免它被意外覆盖,例如
If the common initialization is done in a method, then the method name should be morespecific, to avoid that it is overriden "accidentally", for example
-(void)commonVideoViewSetup;
这篇关于在Objective C中使用静态init时的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!