目标C:我的自定义-init方法不被调用 [英] Objective C: My custom -init method not getting called
问题描述
我有一个类,我从UIView派生,我想创建一个-init类,像这样:
- (id)init
{
if(self = [super init]){
//这里的初始化
}
return self;不幸的是,我知道一个事实,-init不会被调用。下面是我如何在我的.h中定义它: - (id)init;
任何人都知道为什么它不被调用?
ADDENDUM:
我发现当我将初始化放在initWithCoder中时,
我添加了initWithFrame但是没有调用。
这是一个在IB中指定的对象。
UIViewController 和 UIView
有两个指定的初始化程序。它们是从 nib
调用的 initWithCoder
和从调用的 initWithFrame
码。 Init
不是这些对象的指定初始化程序。
如果你想覆盖这两个基地,你可以做这是:
- (void)initializationCodeMethod {
< #Initialization Code Here#
}
- (id)initWithFrame:(CGRect)frame {
if((self = [super initWithFrame:frame])){
[self initializationCodeMethod];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if((self = [super initWithCoder:aDecoder])){
[self initializationCodeMethod];
}
return self;
}
I have a class that I'm deriving from UIView, and I wanted to create a -init class for it like so:
- (id) init
{
if (self = [super init]) {
// my initializations here
}
return self;
}
Unfortunately I know for a fact that -init is not getting called. Here is how I define it in my .h:
-(id)init;
Anybody know why it's not getting called?
ADDENDUM:
I found that when I put my initialization in initWithCoder, it is run just fine.
I added initWithFrame but that wasn't called.
This is for an object that I specified in IB.
解决方案 There are two designated initializers for UIViewController
and UIView
they are initWithCoder
called from nib
, and initWithFrame
called from code. Init
is not the designated initializer for those objects.
If you want to cover both bases you can do something like this:
-(void)initializationCodeMethod{
<#Initialization Code Here#>
}
-(id)initWithFrame:(CGRect)frame{
if ((self = [super initWithFrame:frame])){
[self initializationCodeMethod];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if ((self = [super initWithCoder:aDecoder])){
[self initializationCodeMethod];
}
return self;
}
这篇关于目标C:我的自定义-init方法不被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文