博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
oc38--类工厂方法在继承中
阅读量:4615 次
发布时间:2019-06-09

本文共 1563 字,大约阅读时间需要 5 分钟。

//  Person.h#import 
@interface Person : NSObject@property int age;/* 什么是类工厂方法: 用于快速创建对象的类方法, 我们称之为类工厂方法 类工厂方法中主要用于 给对象分配存储空间和初始化这块存储空间 规范: 1.一定是类方法 + 2.方法名称以类的名称开头, 首字母小写 3.一定有返回值, 返回值是id/instancetype*/+ (instancetype)person;+ (instancetype)personWithAge:(int)age;@end
//  Person.m#import "Person.h"@implementation Person+ (instancetype)person{    // return [[Person alloc] init];    // 注意: 以后但凡自定义类工厂方法, 在类工厂方法中创建对象一定不要使用类名来创建    // 一定要使用self来创建    // self在类方法中就代表类对象, 到底代表哪一个类对象呢?    // 谁调用当前方法, self就代表谁, 子类调用,self就是子类的类对象。    return [[self alloc] init];}+ (instancetype)personWithAge:(int)age{    //Person *p = [[Person alloc] init];    //这样写,即使子类调用 返回的就永远是Person,    Person *p = [[self alloc] init];    //子类调用这里的self是子类对象,此时的p也是子类对象。    p.age = age;    return p;}@end
//  Student.h#import "Person.h"@interface Student : Person   //继承Person,就有了Person的age属性和person,personWithAge方法,以及自己的no属性,@property int no;@end
//  Student.m#import "Student.h"@implementation Student@end
//  main.m//  类工厂方法在继承中的注意点#import 
#import "Student.h"int main(int argc, const char * argv[]) { Student *stu = [Student person]; // 调用父类的person方法,父类用的是self,所以就是创建一个子类Student对象 [[Person alloc] init]; stu.age = 55; NSLog(@"age = %i", stu.age); stu.no = 888; NSLog(@"no = %i", stu.no); Person *p = [Person person]; p.age = 100; //p.no = 200; Student *stu1 = [Student personWithAge:30]; Person *p1 = [Person personWithAge:30]; stu1.no = 888; return 0;}

 

转载于:https://www.cnblogs.com/yaowen/p/7417857.html

你可能感兴趣的文章
angular 防购物车特效
查看>>
Android中的XML解析
查看>>
CentOS7安装Redis4.0
查看>>
HDU 5973 Aninteresting game 威佐夫博奕(Wythoff Game)
查看>>
DNS——Bind服务
查看>>
集群中几种session同步解决方案的比较
查看>>
mongoDB: cursor not found on server
查看>>
SSH登陆响应慢的问题
查看>>
android 有效载荷大图,避OOM
查看>>
The Swift Programming Language中国完整版
查看>>
项目管理心得:一个项目经理的个人体会、经验总结
查看>>
原来腾讯还出过一个开源项目libco
查看>>
DEP
查看>>
MVC项目综述
查看>>
[luogu4705] 玩游戏
查看>>
Android || IOS录制mp3语音文件方法
查看>>
3.这个月有几天?
查看>>
HTML基本文件, CSS基础
查看>>
从程序类转向销售类工作,该如何进行?
查看>>
Mkdir方法
查看>>