Chi*_*ong 18 iphone class-design initialization subclass
我想在类中编写一些方法,以便其他类可以使用调用这些方法[instance methodName:Parameter].
如果类是其子类UIViewController,我可以用initWithNibName它来初始化它.但我想在NSObject的子类中编写方法,我该如何初始化它?
Jan*_*les 57
iphony是正确的,但他或她并没有说你需要自己编写init方法.你的init方法通常应该是这样的:
- (id) init
{
if (self = [super init])
{
myMember1 = 0; // do your own initialisation here
myMember2 = 0;
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
虽然苹果文档说
NSObject类中定义的init方法不进行初始化; 它只是回归自我.
一个人可能只想写作
- (id) init
{
myMember1 = 0; // do your own initialisation here
myMember2 = 0;
return self;
}
Run Code Online (Sandbox Code Playgroud)
这是错误的,不遵循文档中明确说明的内容:
在此(init)方法的自定义实现中,您必须调用super的指定初始化程序,然后初始化并返回新对象.
必须.不应该,也不应该,等等.
您不应该假设NSObject的init在将来不会改变; 也不是自定义类派生的超类.
Chi*_*ong -2
我发现这可能有效:
TheClass *newObject = [[TheClass alloc] init];
//do something here
[newObject release];Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23329 次 |
| 最近记录: |