继承
- 在OC中没有多继承,只有多重继承;只有public继承(不同于c++)
- 所有类型都有公共基类NSObject
通过继承可以:
- 继承父类
- 增加本类实例变量和方法(子类不能和父类同名)
- 覆盖父类的方法
方法的覆盖
与c++的不同点在于:
- 在使用覆盖时,不需要在头文件声明,只需要直接实现
- oc都在堆区分配内存,而执行操作目标都是指针指向的对象,而不是指针本身
覆盖NSObject基类
- NSObject类里实现了dealloc init alloc release 方法,前两者需要在子类重载,后两者不需要
- 如果想直接用NSLog输出对象,需要覆盖NSObject中的description方法(类似于c++中的运算符重载)
-(NSString) description{
NSString*str=[NSString stringWithFormat:@"x=%d, y=%d", x,y];
return str;
}
NSLog("%@", str);
多级继承下的初始化
- 子类中应重载init方法,每个类都应该有指定初始化方法
- init方法调用自己类中的指定初始化,指定初始化调用父类的指定初始化
多级继承下的self和super
has a
A类拥有B类的一个对象成员b,如果希望在程序进程中修改b时不影响b在A类中的赋值,需要用copy
//.h
@property(nonatomic,copy)ASPoint* origin;
//.m
-(id)initWithOrigin:(ASPoint*)aPoint width:(double)aWidth height:(double)aHeight{
if(self = [super init]) {
//正常情况下:origin = [aPoint retain];
origin = [[ASPoint alloc]initWithX:aPoint.x y:aPoint.y];
//类似于:ASPoint * tmp = [[ASPoint alloc]initWithX:aPoint.x y:aPoint.y];
//origin = tmp;
//demo.m
ASPoint * p1 = [[ASPoint alloc] initWithX:2 y:3];
ASRectangle * rec = [[ASRectangle alloc]initWithOrigin:p1 width:10 height:15];
NSLog(@"%g",[rec area]);
NSLog(@"%@",rec.origin);//(2,3)
p1.x = 100;//修改p1的值
NSLog(@"%@",rec.origin);//依然是(2,3)
[rec release];
[p1 release];
注意:这里需要重载dealloc方法,和description方法