单例源代码
Singleton.h
// .h
#define singleton_interface(class) + (instancetype)shared##class;
// .m
#define singleton_implementation(class) \
static class *_instance; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
\
return _instance; \
} \
\
+ (instancetype)shared##class \
{ \
if (_instance == nil) { \
_instance = [[class alloc] init]; \
} \
\
return _instance; \
}
使用方法:
创建一个你想使用单例的类,例如UserInfo
UserInfo.h
#import <Foundation/Foundation.h>
#import "Singleton.h"
@interface UserInfo : NSObject
singleton_interface(UserInfo);
@property (nonatomic, copy) NSString *userName;//用户名
@property (nonatomic, copy) NSString *password;//密码
@end
UserInfo.m
#import "UserInfo.h"
@implementation UserInfo
singleton_implementation(UserInfo)
@end
在需要使用单例的地方只需调用“sharedclass”方法
UserInfo *userInfo = [UserInfo sharedUserInfo];
userInfo.userName = _userName.text;
userInfo.password = _password.text;