美文网首页
OC-消息转发多继承

OC-消息转发多继承

作者: 紫云夕月 | 来源:发表于2021-08-24 14:21 被阅读0次
    #import "ViewController.h"
    #import "Programmer.h"
    #import "Singer.h"
    #import "Artist.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        Programmer * grammer = [Programmer new];
        // 在performSelector中使用NSSelectorFromString会造成警告
        // 可以通过设置不检测performSelector内存泄露关闭警告
        //[grammer performSelector:NSSelectorFromString(@"sing") withObject:nil];
        //或者通过类型强转来实现,无警告
        [(Artist*)grammer draw];
        [(Singer*)grammer sing];
    }
    @end
    
    #import <Foundation/Foundation.h>
    
    @interface Programmer : NSObject
    
    @end
    
    #import "Programmer.h"
    #import "Singer.h"
    #import "Artist.h"
    
    @implementation Programmer
    // 通过消息转发实现多继承
    - (id)forwardingTargetForSelector:(SEL)aSelector {
        Singer * singer = [[Singer alloc] init];
        Artist * artist = [[Artist alloc] init];
        
        if ([singer respondsToSelector:aSelector]) {
            return singer;
        }
        else if ([artist respondsToSelector:aSelector]) {
            return artist;
        }
        return nil;
    }
    @end
    
    #import <Foundation/Foundation.h>
    
    @interface Artist : NSObject
    // 画家可以绘画
    - (void)draw;
    @end
    
    #import "Artist.h"
    
    @implementation Artist
    -(void)draw {
       NSLog(@"I can draw");
    }
    @end
    
    #import <Foundation/Foundation.h>
    
    @interface Singer : NSObject
    // 歌手会唱歌
    - (void)sing;
    @end
    
    #import "Singer.h"
    
    @implementation Singer
    - (void)sing {
        NSLog(@"I can sing");
    }
    @end
    

    相关文章

      网友评论

          本文标题:OC-消息转发多继承

          本文链接:https://www.haomeiwen.com/subject/djcuvltx.html