美文网首页
组合与聚合

组合与聚合

作者: 我不白先生 | 来源:发表于2020-09-15 18:50 被阅读0次

    1类与对象(续)
    1.1dealloc方法
    1.1.1该方法是从NSObject类中欧诺个继承的
    1.1.2该方法在对象的堆空间被释放之前由ARC调用
    2.组合与聚合
    2.1是指两个(或以上)类之间的一种关系
    2.2是(一个)整体类与(多个)部分类之间的关系
    2.3组合是强关系,即同生共死

    2.3聚合是弱关系,非同生共死
    习题
    TRAnimal.h

    #import <Foundation/Foundation.h>
    #import "TRHead.h"
    #import "TRLimb.h"
    #import "TRTrunk.h"
    NS_ASSUME_NONNULL_BEGIN
    @interface TRAnimal : NSObject
    {
        TRHead *_head;
        TRLimb *_limb;
        TRTrunk *_trunk;
    }
    @end
    

    TRAnimal.m

    #import "TRAnimal.h"
    
    @implementation TRAnimal
    -(instancetype)init
    {
        self = [super init];
        if(self)
        {
            NSLog(@"动物诞生了");
            _head = [[TRHead alloc] init];
            _limb = [[TRLimb alloc] init];
            _trunk =[[TRTrunk alloc]init];
        }
        return self;
    }
    -(void)dealloc
    {
        NSLog(@"动物死亡了");
    }
    @end
    

    ViewController.m

    #import "ViewController.h"
    #import "TRAnimal.h"
    @interface ViewController ()
    @end
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        TRAnimal *a = [[TRAnimal alloc] init];
        NSLog(@"--------");
    }
    

    2.4聚合是弱关系,非同生共死
    TRAnimal.h

    #import <Foundation/Foundation.h>
    #import "TRHead.h"
    #import "TRLimb.h"
    #import "TRTrunk.h"
    NS_ASSUME_NONNULL_BEGIN
    
    @interface TRAnimal : NSObject
    
    @property TRHead *head;
    @property TRLimb *limb;
    @property TRTrunk *trunk;
        
    
    @end
    

    TRAnimal.m

    #import "TRAnimal.h"
    
    @implementation TRAnimal
    -(instancetype)init
    {
        self = [super init];
        if(self)
        {
            NSLog(@"动物诞生了");
    
        }
        return self;
    }
    -(void)dealloc
    {
        NSLog(@"动物死亡了");
    }
    @end
    

    ViewController.m

    #import "ViewController.h"
    #import "TRAnimal.h"
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        TRHead *h = [[TRHead alloc] init];
        TRLimb *l = [[TRLimb alloc] init];
        TRTrunk *t = [[TRTrunk alloc] init];
        NSLog(@"------");
        {
            TRAnimal *a = [[TRAnimal alloc] init];
            a.head = h;
            a.limb = l;
            a.trunk = t;
        }
        NSLog(@"=======");
    }
    

    相关文章

      网友评论

          本文标题:组合与聚合

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