// 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;}