创建一个类的对象时,一定要调用它们的默认初始化器或者指定的初始化器进行初始化
具体:创建一个 Monkey 继承自NSObject 的类,定义3个实例变量
#import <Foundation/Foundation.h>
@interface Monkey : NSObject
- (id)initWithWeight: (int)weight;
- (id)initWithWeight:(int)weight height:(int)height;
- (id)initWithWeight:(int)weight height:(int)height gender:(int)gender;
@end
@interface Monkey ()
{
int _weight;
int _height;
int _gender;
}
@end
@implementation Monkey
- (id)init
{
self = [self initWithWeight:0 height:0 gender:0];
return self;
}
- (id)initWithWeight:(int)weight
{
self = [self initWithWeight:weight height:0 gender:0];
return self;
}
- (id)initWithWeight:(int)weight height:(int)height
{
self = [self initWithWeight:weight height:height gender:0];
return self;
}
//Default initializer/Designated initializer
- (id)initWithWeight:(int)weight height:(int)height gender:(int)gender
{
self = [super init];
if (self) {
_weight = weight;
_height = height;
_gender = gender;
}
return self;
}
@end
在创建一个DeadMonkey 继承自Monkey
#import <Foundation/Foundation.h>
#import "Monkey.h"
@interface DeadMonkey : Monkey
@end
@implementation DeadMonkey
- (id)initWithWeight:(int)weight height:(int)height gender:(int)gender
{
self = [super initWithWeight:10 height:10 gender:10];
if (self) {
}
return self;
}
@end
再去调用这初始化方法观察
Monkey *monkey1 = [[Monkey alloc] initWithWeight: 20 height:30];
默认初始化方法的使用
DeadMonkey *deadMonkey = [[DeadMonkey alloc] init];
默认初始化方法的过程
最新推荐文章于 2022-10-04 22:42:20 发布