- Person.h
- #import<foundation/Foundation.h>
- @interfacePerson : NSObject {
- NSString *someProperty;
- }
- @property(nonatomic, retain) NSString *someProperty;
- +(id)Person;
- @end
复制代码- Person.m
- #import"Person.h"
- @implementationPerson
- @synthesizesomeProperty;
- #pragmamark Singleton Methods
- +(id)Person{
- static Personr *Person= nil;
- static dispatch_once_tonceToken;
- dispatch_once(&onceToken, ^{
- Person= [[self alloc] init];
- });
- return Person;
- }
- -(id)init {
- if (self = [super init]) {
- someProperty =[[NSString alloc] initWithString:@"Default Property Value"];
- }
- return self;
- }
- @end
复制代码 通过创建一个静态的Person对象,使用GCD的dispatch_once确保只会创建一次实例,并且保证线程安全。单例模式最容易忽视的就是多线程
|