zoukankan      html  css  js  c++  java
  • OC 复合

    在Objective-C中复合是通过包含作为实例变量的对象指针实现的

    严格来说,只有对象间的组合才叫复合

    --------------------Car.h---------------------------

    #import <Foundation/Foundation.h>

    #import "Wheel.h"

    @interface Car : NSObject

     @property Wheel *wheel1;

    @property Wheel *wheel2;

    @property Wheel *wheel3;

    @property Wheel *wheel4;

    /*

        1.如果复合的属性是另外一个类的类型,那么在使用之前记得初始化该属性

        2.如果想要在[内部没有初始化复合属性]的前提下使用的话,需要传入的参数必须是已经初始化过的

     */

    @end

    -------------------Car.m-------------------------

    #import "Car.h"

    @implementation Car 

    //内部初始化复合属性

    - (instancetype)init

    {

        self = [super init];

        if (self) {

            self.wheel1 = [[Wheel alloc] init];

            self.wheel2 = [[Wheel alloc] init];

            self.wheel3 = [[Wheel alloc] init];

            self.wheel4 = [[Wheel alloc] init];

        }

        return self;

    }

    - (NSString *)description

    {

        return [NSString stringWithFormat:@" wheel1.type:%@  wheel2.type:%@  wheel3.type:%@  wheel4.type:%@", self.wheel1.type, self.wheel2.type, self.wheel3.type, self.wheel4.type];

    }

    @end

    ---------------------Wheel------------------------

    #import <Foundation/Foundation.h>

    @interface Wheel : NSObject

    @property NSString *type;

    @end

    #import "Wheel.h"

    @implementation Wheel

    @end

    --------------------测试文件--------------------------

    #import <Foundation/Foundation.h>

    #import "Wheel.h"

    #import "Car.h"

    int main(int argc, const char * argv[]) {

        @autoreleasepool {

            

            

            Car *car = [[Car alloc] init];

    //        外部初始化复合属性

    //        Wheel *wheel1 = [[Wheel alloc] init];

    //        wheel1.type = @"法拉利的轮子1";

    //        Wheel *wheel2 = [[Wheel alloc] init];

    //        wheel2.type = @"法拉利的轮子2";

    //        Wheel *wheel3 = [[Wheel alloc] init];

    //        wheel3.type = @"法拉利的轮子3";

    //        Wheel *wheel4 = [[Wheel alloc] init];

    //        wheel4.type = @"法拉利的轮子4";

    //        

    //        car.wheel1 = wheel1;

    //        car.wheel2 = wheel2;

    //        car.wheel3 = wheel3;

    //        car.wheel4 = wheel4;

            

            

            

            car.wheel1.type=@"宝马的轮子1";

            car.wheel2.type=@"宝马的轮子2";

            car.wheel3.type=@"宝马的轮子3";

            car.wheel4.type=@"宝马的轮子4";

            

            NSLog(@"%@",car);

        }

        return 0;

    }

  • 相关阅读:
    在同一asp.net website工程中引用app_code中定义的control
    perl中的ppm 安装包时,如果通过代理如何下载最新的包及离线安装的问题
    利用htc s900拨号上联通3G网
    转载一篇有关ramdisk 的使用的文章
    .net dataTable对象的处理性能
    TPlink 340G+设置外网访问内网机器
    C++中的const关键字(zz)
    存在 汪峰
    ETW (Event Tracing for Windows)介绍
    理解smart pointer之一(auto_ptr介绍)
  • 原文地址:https://www.cnblogs.com/oc-bowen/p/5028815.html
Copyright © 2011-2022 走看看