pragma mark 类工厂方法在继承中的注意点
pragma mark 概念
/*
#warning 类工厂方法 简化
+ (instancetype)person
{
// 一点要使用 self来创建
return [[self alloc]init];
}
*/
pragma mark 代码a
#import <Foundation/Foundation.h>
#pragma mark 类
#import "Student.h"
#pragma mark main函数
int main(int argc, const char * argv[])
{
#warning 父类指针 指向 子类对象 才是多态
#warning 子类指针 指向 父类对象 什么都不是 是一个错误的写法
/*
Student *s = [Student person]; // [Student person] == [[Person alloc]init] //
Person *p = [Person person];
// s.age = 33;
// NSLog(@"age = %i",s.age);
s.no = 100;
// -[Person setNo:]: unrecognized selector sent to instance 0x100102bc0'
NSLog(@"no = %i",s.no);
*/
Student *s = [Student personWithAge:33];
s.no = 222;
NSLog(@"%i",[s no]);
return 0;
}
Person.h //人类
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property int age;
#warning 什么是类工厂方法
/*
什么是类工厂方法:
用于 快速创建 对象的方法, 我们称之为工厂方法
类工厂方法中 主要用于 给对象分配存储空间和初始化
规范:
1. 一定是类方法
2. 方法名称以类名开头, 首字母小写
3. 一定有返回值, 返回值是 id / instancetype
*/
+ (instancetype)person;
#warning 类工厂方法带参数
+ (instancetype)personWithAge:(int)age;
@end
Person.m
#import "Person.h"
@implementation Person
#warning 类工厂方法
/*
+ (instancetype)person
{
// 1. 分配存储空间
// 2. 初始化
// 3. 返回对象
Person *p = [Person alloc];
Person *p1 = [p init];
p1.age = 30;
NSLog(@"age = %i",p1.age);
return p1;
}
*/
#warning 类工厂方法 简化
+ (instancetype)person
{
// return [[Person alloc]init];
#warning !!! 注意: 以后但凡 自定义类方法, 在类工厂方法中创建对象 一定不要使用类名来创建
// 一点要使用 self来创建
// self 在 类方法中 就代表类对象, 到底代表那个一个类对象呢
// 谁调用 当前方法 , self 就代表谁
return [[self alloc]init];
}
#warning 类工厂方法带参数
+ (instancetype)personWithAge:(int)age
{
// Person *p = [[Person alloc]init];
#warning !!! 注意: 以后但凡 自定义类方法, 在类工厂方法中创建对象 一定不要使用类名来创建
// 这里还是多态 Person 是父类 self有可能是子类 比如 student
Person *p = [[self alloc]init];
p.age = age;
return p;
}
@end
Studnet.h //学生类 (人类的子类)
#import "Person.h"
@interface Student : Person
@property int no;
@end
Studnet.m
#import "Student.h"
@implementation Student
@end
—