zoukankan      html  css  js  c++  java
  • OC-重写构造方法

    from : http://www.cnblogs.com/wendingding/p/3706883.html

    重写构造方法的目的是:让对象方法一创建出来,成员变量就会有一些固定的值。

    示例

    //
    //  Person.h
    //  WDDGouzaofangfaTest
    //
    //  Created by LiuChanghong on 15/9/25.
    //  Copyright © 2015年 LiuChanghong. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    
    @property int age;
    
    @end
    Person.h
    //
    //  Person.m
    //  WDDGouzaofangfaTest
    //
    //  Created by LiuChanghong on 15/9/25.
    //  Copyright © 2015年 LiuChanghong. All rights reserved.
    //
    
    #import "Person.h"
    
    @implementation Person
    
    
    //重写构造方法
    - (instancetype)init
    {
        //初始化对象,以拥有父类成员变量
        self = [super init];
        if (self) {
            //初始化对象自有成员变量
            _age = 10;
        }
        //返回一个已经初始化完成的对象
        return self;
    }
    
    @end
    Person.m
    //
    //  Student.h
    //  WDDGouzaofangfaTest
    //
    //  Created by LiuChanghong on 15/9/25.
    //  Copyright © 2015年 LiuChanghong. All rights reserved.
    //
    
    #import "Person.h"
    
    @interface Student : Person
    
    @property int number;
    
    @end
    Student.h
    //
    //  Student.m
    //  WDDGouzaofangfaTest
    //
    //  Created by LiuChanghong on 15/9/25.
    //  Copyright © 2015年 LiuChanghong. All rights reserved.
    //
    
    #import "Student.h"
    
    @implementation Student
    
    //重写构造方法
    - (instancetype)init
    {
        //初始化对象,以拥有父类(person)的成员变量,包括age
        self = [super init];
        if (self) {
            _number = 10010;
        }
        return self;
    }
    
    @end
    Student.m

    测试主程序

    //
    //  main.m
    //  WDDGouzaofangfaTest
    //
    //  Created by LiuChanghong on 15/9/25.
    //  Copyright © 2015年 LiuChanghong. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    #import "Student.h"
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            
            Student *student = [Student new];//等同于[[Student alloc]init]
            NSLog(@"学生的年龄为%d岁,学号为%d",student.age,student.number);
            
        }
        return 0;
    }
    测试主程序

    输出结果

  • 相关阅读:
    详解SQL Server的两个存储过程:sp_MSforeachtable/sp_MSforeachdb
    使用WorkService创建定时任务
    Mahout下个性化推荐引擎Taste介绍
    Apache Mahout中的机器学习算法集
    内网信息收集笔记 楼下的小可怜
    关于linux的suid提权 楼下的小可怜
    Cobalt Strike初探 楼下的小可怜
    Google hacking 楼下的小可怜
    Git和Repo扫盲——如何取得Android源代码 zt
    Howto find native code memory leak in Android
  • 原文地址:https://www.cnblogs.com/liuchanghong/p/4837898.html
Copyright © 2011-2022 走看看