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;

    }

  • 相关阅读:
    关于MySQL数据库优化的部分整理
    PHP跨域form提交
    px、dp和sp,这些单位有什么区别?
    301和302 Http状态有啥区别?
    PHP HTTP请求
    php的http_build_query使用
    nginx ssi 模块
    MongoDB学习笔记(一) MongoDB介绍及安装(摘)
    Django Admin 录入中文错误解决办法
    关于python字符串连接的操作
  • 原文地址:https://www.cnblogs.com/oc-bowen/p/5028815.html
Copyright © 2011-2022 走看看