iOS 單例模式簡單實例


 單例模式主要實現唯一實例,存活於整個程序范圍內,一般存儲用戶信息經常用到單例,比如用戶密碼,密碼在登錄界面用一次,在修改密碼界面用一次,而使用單例,就能保證密碼唯一實例。如果不用單例模式,init 兩個的實例的堆棧地址不一樣,所以存放的數據的位置也不一樣,當其中一個數據改變,另一個數據依然不變。單例模式的代碼如下

 .h文件

#ifndef Singleton_h
#define Singleton_h

@interface Singleton : NSObject
@property (nonatomic, copy) NSString *pass;
+ (Singleton *) sharedInstance;

@end

.m文件

#import <Foundation/Foundation.h>
#import "Singleton.h"

@implementation Singleton
static id sharedSingleton = nil;
+ (id)allocWithZone:(struct _NSZone *)zone
{
if (sharedSingleton == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedSingleton = [super allocWithZone:zone];    
});
}
return sharedSingleton;
}

- (id)init
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSingleton = [super init];
    });
    return sharedSingleton;
}

+ (instancetype)sharedInstance
{
return [[self alloc] init];
}
+ (id)copyWithZone:(struct _NSZone *)zone
{
return sharedSingleton;
}
+ (id)mutableCopyWithZone:(struct _NSZone *)zone
{
return sharedSingleton;
}


@end

宏實現單例

#ifndef Singleton_m_h
#define Singleton_m_h

// 幫助實現單例設計模式

// .h文件的實現
#define SingletonH(methodName) + (instancetype)shared##methodName;

// .m文件的實現
#if __has_feature(objc_arc) // 是ARC
#define SingletonM(methodName) \
static id _instace = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
} \
return _instace; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super init]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
}

#else // 不是ARC

#define SingletonM(methodName) \
static id _instace = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
} \
return _instace; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super init]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
\
- (oneway void)release \
{ \
\
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return 1; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
}
#endif /* Singleton_m_h */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM