IOS开发中单例模式使用详解
生活随笔
收集整理的這篇文章主要介紹了
IOS开发中单例模式使用详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一、基本概念
單例模式是一種常用的軟件設計模式。在它的核心結構中只包含一個被稱為單例類的特殊類。通過單例模式可以保證系統中一個類只有一個實例而且該實例易于外界訪問。
第二、在IOS中使用單例模式的情況
1.如果說創建一個對象會耗費很多系統資源,那么此時采用單例模式,因為只需要一個實例,會節省alloc的時間
2.在IOS開發中,如果很多模塊都要使用同一個變量,此時如果把該變量放入單例類,則所有訪問該變量的調用變得很容易,否則,只能通過一個模塊傳遞給另外一個模塊,這樣增加了風險和復雜度
第三、創建單例模式的基本步驟
1.聲明一個單例對象的靜態實例,并初始化為nil
2.聲明一個類的工廠方法,生成一個該類的實例,并且只會生成一個
3.覆蓋allcoWithZone方法,確保用戶在alloc 時,不會產生一個多余的對象
4.實現NSCopying協議,覆蓋release,autorelease,retain,retainCount方法,以確保只有一個實例化對象
5.在多線程的環境中,注意使用@synchronized關鍵字?
?
// // UserContext.h // SingleDemo // // Created by andyyang on 9/30/13. // Copyright (c) 2013 andyyang. All rights reserved. //#import <Foundation/Foundation.h>@interface UserContext : NSObject @property (nonatomic,retain) NSString *username; @property(nonatomic,retain)NSString *email; +(id)sharedUserDefault; @end?
?
?
// // UserContext.m // SingleDemo // // Created by andyyang on 9/30/13. // Copyright (c) 2013 andyyang. All rights reserved. //#import "UserContext.h"static UserContext *singleInstance=nil; @implementation UserContext+(id)sharedUserDefault {if(singleInstance==nil){@synchronized(self){if(singleInstance==nil){singleInstance=[[[self class] alloc] init];}}}return singleInstance; }+ (id)allocWithZone:(NSZone *)zone; {NSLog(@"HELLO"); if(singleInstance==nil) {singleInstance=[super allocWithZone:zone]; }return singleInstance; } -(id)copyWithZone:(NSZone *)zone {NSLog(@"hello");return singleInstance; } -(id)retain {return singleInstance; } - (oneway void)release{ } - (id)autorelease {return singleInstance; }- (NSUInteger)retainCount {return UINT_MAX; }@end?
#import <Foundation/Foundation.h> #import "UserContext.h"int main(int argc, const char * argv[]) {@autoreleasepool {UserContext *userContext1=[UserContext sharedUserDefault];UserContext *userContext2=[UserContext sharedUserDefault];UserContext *userContext3=[[UserContext alloc] init];UserContext *userContext4=[userContext1 copy];// insert code here...NSLog(@"Hello, World!");}return 0; }
result:
?
總結
以上是生活随笔為你收集整理的IOS开发中单例模式使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux系统开机过程描述
- 下一篇: objective-C 自定义对象归档的