Student.h
#import <Foundation/Foundation.h> @interface Student : NSObject @property (nonatomic, copy) NSString *name; - (instancetype)initWithName:(NSString *)name; //单例:default stand share开头 + (instancetype)defaultStudent; @end
Student.m
#import "Student.h" @implementation Student static Student *stu = nil; + (instancetype)defaultStudent { if (stu == nil) { stu = [[Student alloc]init]; } return stu; } - (instancetype)init { self = [super init]; if (self) { _name = @"default"; } return self; } - (instancetype)initWithName:(NSString *)name { self = [super init]; if (self) { _name = name; } return self; } @end
main.m
#import <Foundation/Foundation.h> #import "Student.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu1 = [Student defaultStudent]; stu1.name = @"小黑"; Student *stu2 = [Student defaultStudent]; stu2.name = @"小花"; Student *stu3 = [Student defaultStudent]; stu3.name = @"小花3"; Student *stu4 = [Student defaultStudent]; stu4.name = @"小花4"; NSLog(@"%@",stu2.name); } return 0; }
输出结果
2015-08-18 16:32:51.805 单例[2425:83353] 小花4
时间: 2024-11-05 06:30:41