单列在ios开发中是一种设计模式,在整个程序的生命周期内,单列类只会被初始化一次。可以用来传值等用途。使用一个简单的列子分别写了oc和swift单列的写法
OC写单列
#import <UIKit/UIKit.h>
@interface gameManager : NSObject
@property(nonatomic,strong)NSString *score;
+ (instancetype) shareGameManager;
- (void)addScore;
@end
上面是 .h 文件内容 ,下面是.m文件内容
#import "gameManager.h"
@implementation gameManager
//废除init方法
- (instancetype)init{
@throw [NSException exceptionWithName:@"错误信息" reason:@"不能调用init方法创建对象" userInfo:nil];
}
- (instancetype)initPrivate{
if (self = [super init]) {
写自己的代码
self.score = 0;
}
return self;
}
+ (instancetype)sharegameManager{
static gameManager * instance = nil;
@synchronized(self) {
if (instance == nil) {
instance = [[self alloc] initPrivate];
}
}
return instance;
}
- (void)addScore{
//供外部调用的方法
self.score += 10;
}
通过 [gameManager shareGameManage].addScore 使用这个单列
swift 写单列
#import Foundation
public class gameManager {
public var score = 0
public static let defaultGameManager = gameManager()
private init(){
只初始化一次,写自己的代码
}
public func addScore{
//供外部调用的方法
score += 10
}
}
通过 let gm = gameManager.defaultGameManager
gm.addScore 调用这个单列的方法
网友评论