美文网首页八天学会OC
第04天OC语言(15):类工厂方法在继承中的注意点

第04天OC语言(15):类工厂方法在继承中的注意点

作者: liyuhong | 来源:发表于2017-07-21 17:33 被阅读13次
    • 不要等到明天,明天太遥远,今天就行动。
    须读:看完该文章你能做什么?

    创建类工厂方法的时候,应该注意的知识

    学习前:你必须会什么?

    什么是类工厂方法


    一、本章笔记
     一、    
          注意: 以后但凡 自定义类工厂方法, 在类工厂方法中 创建对象 一定不要使用类名创建
          一定要使用self来创建
          self 在类方法中 代表 类对象 , 到底代表哪一个类对象呢?
          调用当前方法,self 就代表谁
     二、
      子类指针 指向 父类对象 (错误写法) Student *s = [Person new];
      父类指针 指向 子类对象 (多态) Person *p = [Student new];
    
    
    二、code
    main.m
    #pragma mark 15-类工厂方法在继承中的注意点
    #pragma mark 概念
    
    /*
     一、    
          注意: 以后但凡 自定义类工厂方法, 在类工厂方法中 创建对象 一定不要使用类名创建
          一定要使用self来创建
          self 在类方法中 代表 类对象 , 到底代表哪一个类对象呢?
          调用当前方法,self 就代表谁
     二、
      子类指针 指向 父类对象 (错误写法) Student *s = [Person new];
      父类指针 指向 子类对象 (多态) Person *p = [Student new];
     */
    
    #pragma mark - 代码
    #import <Foundation/Foundation.h>
    #pragma mark 类
    #import "Student.h"
    #pragma mark - main函数
    int main(int argc, const char * argv[])
    {
        /*
        Student *s = [Student person]; // 本质等于 [[Person alloc]init] // 错误写法
    //    Person *p = [Person person];
        // 子类指针 指向 父类对象 (错误写法)
        // 父类指针 指向 子类对象 (多态)
        
    //    s.age = 55;
    //    NSLog(@"age = %i",s.age);
        s.no = 98;
        NSLog(@"no = %i",s.no);
         */
        
        Student *s =[Student personWithAge:33];
        s.no = 88; // -[Person setNo:]: unrecognized selector sent to instance 0x100204bd0'
        
        return 0;
    }
    
    
    Person
    >>>.h
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    
    @property int age;
    
    + (instancetype)person;
    + (instancetype)personWithAge:(int)age;
    
    @end
    
    >>>.m
    #import "Person.h"
    
    @implementation Person
    + (instancetype)person
    {
    //    return [[Person alloc]init];
        // 注意: 以后但凡 自定义类工厂方法, 在类工厂方法中 创建对象 一定不要使用类名创建
        // 一定要使用self来创建
        // self 在类方法中 代表 类对象 , 到底代表哪一个类对象呢?
        // 调用当前方法,self 就代表谁
        return [[self alloc]init];
    }
    
    + (instancetype)personWithAge:(int)age
    {
    //    Person *p = [[Person alloc]init];
        Person *p = [[self alloc]init];
        p.age = age;
        
        return p;
    }
    @end
    
    
    Student
    >>>.h
    #import "Person.h"
    
    @interface Student : Person
    
    @property int no;
    
    @end
    
    >>>.m
    #import "Student.h"
    
    @implementation Student
    
    @end
    
    

    相关文章

      网友评论

        本文标题:第04天OC语言(15):类工厂方法在继承中的注意点

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