在iOS开发中,单例Sington是一种比较常用的设计模式。
当然,写法多种多样,不过要注意单例的特性(内存中只有一个地址)。
Swift写法
// final 关键字说明这个类不希望被继承和重写qq
final class UserInfoSingle: NSObject {
var userName:String?
var userPWD:String?
//退出登录方法
func logoutAction() {
//清空数据
UserInfoSingle.shared.userName = nil
UserInfoSingle.shared.userPWD = nil
}
static let shared = UserInfoSingle.init()
private override init(){}
}
//使用单例
UserInfoSingle.shared.logoutAction()
UserInfoSingle.shared.userName = "steve"
UserInfoSingle.shared.userPWD = "000000"
OC写法
//创建单例,并且添加属性,实例方法
// UserInfo.h
#import <Foundation/Foundation.h>
@interface UserInfo : NSObject
@property (nonatomic,strong) NSString * userName;
@property (nonatomic,strong) NSString * userPWD;
+ (instancetype) shareInstance ;
- (void) logoutAction;
@end
// UserInfo.m
#import "UserInfo.h"
@implementation UserInfo
static UserInfo* _instance = nil;
+(instancetype) shareInstance {
static dispatch_once_t onceToken ;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init] ;
}) ;
return _instance ;
}
- (void) logoutAction {
UserInfo.shareInstance.userName = nil;
UserInfo.shareInstance.userPWD = nil;
}
@end
//使用单例
// ViewController.m
#import “UserInfo.h"
UserInfo.shareInstance.userName = @"steve";
UserInfo.shareInstance.userPWD = @"000000";
[UserInfo.shareInstance logoutAction];
网友评论