new方法的实现原理
Posted zhchoutai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了new方法的实现原理相关的知识,希望对你有一定的参考价值。
// // main.m // 04-new方法的实现原理 #import <Foundation/Foundation.h> #import "Person.h" #import "Student.h" int main(int argc, const char * argv[]) { /* Person * p = [[Person alloc] init]; [p run]; Person * p1 = [Person new]; [p1 run]; Person * p2 = [Person person]; [p2 run]; Student * stu = [Student new]; [stu sleep]; // Dog *dog = [[Animal alloc]init ]; Student * stu2 = [Student person]; [stu2 sleep]; */ // Person * person = [[Person alloc] initWithName:@"笑着"]; /* Person * per = [Person personWithName:@"xiaozhe"]; [per run]; NSLog(@"%@",per); Student * stu = [Student personWithName:@"奶茶"]; [stu sleep]; NSLog(@"%@",stu); */ // NSString * str = [NSString string] // NSArray * array = [NSArray arraywi] Student * stu = [Student studetWithName:@"笑着"]; [stu sleep]; NSLog(@"%@",stu); return 0; }
#import <Foundation/Foundation.h> @interface Person : NSObject @property NSString * name; @property int age; - (id)initWithName:(NSString *)name; - (void)run; +(id)person; +(id)personWithAge:(int)age; +(id)personWithName:(NSString *)name; +(id)personWithName:(NSString *)name andAge:(int)age; @end
#import "Person.h" @implementation Person - (id)initWithName:(NSString *)name { if (self = [super init]) { _name = name; } return self; } +(id)person { // // Person * p = [[Person alloc] init]; //谁调用。他就代表谁 Person * p = [[self alloc] init]; //[[Person alloc] init] //[[Sutdent alloc] init] return p; } +(id)personWithName:(NSString *)name { /* Person * person = [[self alloc] initWithName:name]; return person; */ Person * person = [self person]; person.name = name; return person; } - (void)run { NSLog(@"人跑起来了"); } - (NSString *)description { return [NSString stringWithFormat:@"name %@", _name]; } @end
#import "Person.h" @interface Student : Person - (void)sleep; +(id)studet; +(id)studetWithName:(NSString *)name; @end
#import "Student.h" @implementation Student +(id)studet { return [self person]; } +(id)studetWithName:(NSString *)name { return [self personWithName:name]; } - (void)sleep { NSLog(@"就爱睡"); } @end
以上是关于new方法的实现原理的主要内容,如果未能解决你的问题,请参考以下文章
RuntimeError: An attempt has been made to start a new process before the current process has...(代码片段