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;

    }

  • 相关阅读:
    Leetcode 122. 买卖股票的最佳时机 II
    Leetcode 121. 买卖股票的最佳时机
    Leetcode 205. 同构字符串
    Leetcode 875. 爱吃香蕉的珂珂
    Leetcode 921. 使括号有效的最少添加
    Leetcode 238. 除自身以外数组的乘积
    评论设置----第二章:创建和管理内容
    其它内容选项----第二章:创建和管理内容
    预览和全展示----第二章:创建和管理内容
    Drupal的主题----第一章:Drupal的介绍
  • 原文地址:https://www.cnblogs.com/oc-bowen/p/5028815.html
Copyright © 2011-2022 走看看