OC学习笔记04--id关键字与构造方法

typedef enum{
	ColorBlack='b',ColorYellow='y',ColorWhite='w'
} Color;

#import<Foundation/Foundation.h>

@interface Pet : NSObject
{
	@private 
	int _age;
	double _weight;
	NSString * _name;
}

- (id)initWithAge:(int)age andWeight:(double)weight andName:
(NSString *)name;

-(id)initTest;

- (NSString *)toString;


@end

@implementation Pet

// 重写init方法,由于是无参构造方法,无法动态给成员变量赋值
- (id)init  
{
	if(self=[super init]) //构造方法中必须调用父类构造方法
	{
		_age=1,_weight=1.0,_name=@"pet";
	}
	return self;
}

//自定义构造方法,可以自定义参数,灵活的给成员变量赋值
- (id)initWithAge:(int)age andWeight:(double)weight andName:(NSString *)name
{
	if(self=[super init])
	{
		_age=age,_weight=weight,_name=name;
	}
	return self;
}

-(id)initTest
{
	if(self=[super init])
	{
		//从结果可知,[super class],[self class]都是指向调用者的类对象
		// 即若由Dog的实例调用,则都指向Dog的类对象,即[Dog class];
		NSLog(@"super=%d,self=%d,superclass=%d,selfclass=%d,Pet=%d",
		super,self,[super class],[self class],[Pet class]);
	}
	return self;
}

- (NSString *)toString
{
	return [NSString stringWithFormat:@"name=%@ ,weight=%.2f ,age=%d",
	_name,_weight,_age]; 
}

@end

@interface Dog : Pet
{
	@private
	Color _furColor;
}

- (id)initWithAge:(int)age andWeight:(double)weight andName:
(NSString *)name andFurColor:(Color)furColor;
@end
@implementation Dog

- (id)init  
{
	if(self=[super init]) 
	{
		_furColor=ColorYellow;
	}
	return self;
}

- (id)initWithAge:(int)age andWeight:(double)weight andName:
(NSString *)name andFurColor:(Color)furColor
{
	//调用父类的有参构造方法给父类成员赋值
	if(self=[super initWithAge:age andWeight:weight andName:name])
	{
		_furColor=furColor;
	}
	return self;
}

-(id)initTest
{
	if(self=[super initTest])
	{
		NSLog(@"Dog=%d",[Dog class]);
	}
	return self;
}

- (NSString *)toString
{
	return [NSString stringWithFormat:@"%@ ,furColor=%c",
	[super toString],_furColor]; 
}

@end


int main()
{
	//id作为万能指针,能指向任意OC对象
	id *p=[[Dog alloc] init];
	NSLog(@"this dog is %@",[p toString]);
	id *p2=[[Dog alloc] initWithAge:4 andWeight:12.2 andName:@"Daisy" 
	andFurColor:ColorWhite];
	NSLog(@"this dog is %@",[p2 toString]);
	id *p3=[[Dog alloc] initTest];
	NSLog(@"p3=%d",p3);
	return 0;
}




/*

id关键字:
typedef struct objc_object {
	 Class isa;
} *id;


//构造对象相关方法伪代码
+ (id)new 
{
	return [[self alloc] init];
}

+ (id)alloc
{
	id obj=(struct objc_object)malloc(父类到子类所有成员变量所占字节数总和);
	return obj;
}

- (id)init
{
	//[self class]返回类指针指向当前对象的类对象
	isa=[self class];
	return self;
}


//重写init方法必须调用[super init]来初始化父类中的成员变量  ---类似java无参constructor
- (id)init
{
	
	if(self=[super init])
	{
		..初始化操作..
	}
	return self;
	
}


//自定义构造方法(一般以init开头)  ---类似java有参构造器
- (id)initWithName:(NSString *)name
{
	if(self=[super init])
	{
		_name=name;
	}
	return self;
}

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值