iOS中的继承

2018-09-05  本文已影响0人  皆为序幕_

概念

@interface Phone : NSObject
@property (nonatomic,strong) NSString *name;
- (void)call;
@end

@implementation Phone
- (void)call{
    NSLog(@"%s",__func__);
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"%@", _name];
}
@end
---------------------------
#import "Phone.h"
@interface IPhone : Phone
@property (nonatomic,copy) NSString *type;
@end
#import "IPhone.h"
@implementation IPhone
- (void)call{
    NSLog(@"%@ %@打电话",self.name,self.type);
}
@end

特点:

继承中方法调用的流程:

首先到子类去找,如果有该方法,就调用子类方法,如果没有,就再到父类去找,如果父类还没有,再到父类的父类去找,如果最后还没有找到,程序会崩溃。

适用继承的场合

不适合继承的场景

优缺点

#import <Foundation/Foundation.h>
@interface Phone : NSObject
@property (nonatomic,strong) NSString *name;
- (void)call;
@end

#import "Phone.h"
@implementation Phone
- (void)call{
    NSLog(@"%s",__func__);
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"%@", _name];
}
@end
-------------
#import "Phone.h"
@interface IPhone : Phone
@property (nonatomic,copy) NSString *type;
@end

#import "IPhone.h"
@implementation IPhone
- (void)call{
    NSLog(@"%@ %@打电话",self.name,self.type);
}
@end
-------------
#import <UIKit/UIKit.h>
#import "Iphone.h"
int main(int argc, char * argv[]) {
    IPhone *phone = [[IPhone alloc]init];
    phone.name = @"iphone";
    phone.type = @"8";
    [phone call];
}

替代继承解决复用需求的解决方案

#import <Foundation/Foundation.h>
@protocol PhoneCall <NSObject>
- (void)call;
@end

------------------
#import "PhoneCall.h"
@interface Phone : NSObject<PhoneCall>
@end

#import "Phone.h"
@implementation Phone
- (void)call{
    NSLog(@"%s",__func__);
}
@end
------------------
#import "PhoneCall.h"
@interface IPhone : NSObject<PhoneCall>
@end

#import "IPhone.h"
@implementation IPhone
- (void)call{
    NSLog(@"%s",__func__);
}
@end
--------------
- (void)viewDidLoad {
    [super viewDidLoad];
    
    IPhone *phone = [[IPhone alloc]init];
    [phone call];
    
    Phone *p = [[Phone alloc]init];
    [p call];
}
上一篇 下一篇

猜你喜欢

热点阅读