永发信息网

ios 可以将单例付值给一个新的对象吗

答案:1  悬赏:60  手机版
解决时间 2021-12-01 09:42
  • 提问者网友:兔牙战士
  • 2021-11-30 13:41
ios 可以将单例付值给一个新的对象吗
最佳答案
  • 五星知识达人网友:你可爱的野爹
  • 2021-11-30 14:26
第一、基本概念单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问。第二、在IOS中使用单例模式的情况1.如果说创建一个对象会耗费很多系统资源,那么此时采用单例模式,因为只需要一个实例,会节省alloc的时间2.在IOS开发中,如果很多模块都要使用同一个变量,此时如果把该变量放入单例类,则所有访问该变量的调用变得很容易,否则,只能通过一个模块传递给另外一个模块,这样增加了风险和复杂度第三、创建单例模式的基本步骤1.声明一个单例对象的静态实例,并初始化为nil2.声明一个类的工厂方法,生成一个该类的实例,并且只会生成一个3.覆盖allcoWithZone方法,确保用户在alloc 时,不会产生一个多余的对象4.实现NSCopying协议,覆盖release,autorelease,retain,retainCount方法,以确保只有一个实例化对象5.在多线程的环境中,注意使用@synchronized关键字 [cpp] view plaincopyprint?// // UserContext.h // SingleDemo // // Created by andyyang on 9/30/13. // Copyright (c) 2013 andyyang. All rights reserved. // #import @interface UserContext : NSObject @property (nonatomic,retain) NSString *username; @property(nonatomic,retain)NSString *email; +(id)sharedUserDefault; @end [cpp] view plaincopyprint?// // 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 [cpp] view plaincopyprint?#import #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; } 在开发中我们可以利用ios提供的方法来实现单例模式:SYNTHESIZE_SINGLETON_FOR_CLASS(MyClassName);将该语句置于@implementation MyClassName声明后,这样你的类自动会变成单例。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯