UserInfoManagerCenter.h
#import <Foundation/Foundation.h>
@interface UserInfoManagerCenter : NSObject
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSNumber *age;
+(instancetype)managerCenter;
@end
UserInfoManagerCenter.m
#import "UserInfoManagerCenter.h"
static UserInfoManagerCenter *center = nil;
@implementation UserInfoManagerCenter
+(instancetype)managerCenter{
static dispatch_once_t predicate;
// 避免產生競爭現像
dispatch_once(&predicate, ^{
center = (UserInfoManagerCenter *)@"UserInfoManagerCenter";
center = [[UserInfoManagerCenter alloc] init];
});
// 防止子類別使用
NSString *classString = NSStringFromClass([self class]);
// 使用方法的class名字與UserInfoManagerCenter不同 就crash
if( [classString isEqualToString:@"UserInfoManagerCenter"] == NO ){
// crash
NSParameterAssert(nil);
}
return center;
}
-(instancetype)init{
NSString *string = (NSString*)center;
if( [string isKindOfClass:[NSString class]] == YES && [string isEqualToString:@"UserInfoManagerCenter"]){
self = [super init];
if( self){
// 防止子類別使用
NSString *classString = NSStringFromClass([self class]);
// 使用方法的class名字與UserInfoManagerCenter不同 就crash
if( [classString isEqualToString:@"UserInfoManagerCenter"] == NO ){
// crash
NSParameterAssert(nil);
}
}
return self;
}else{
return nil;
}
}
@end
使用
UserInfoManagerCenter *center = [UserInfoManagerCenter managerCenter];
NSLog(@"%@",center.name);
沒有留言:
張貼留言