iOS_Skill_CollectiOS点点滴滴

iOS避免滥用单例

2016-01-28  本文已影响1906人  AKyS佐毅

单例模式:

使用单例模式需要注意的问题

举例说明错误的单例使用

         #import <Foundation/Foundation.h>
         @interface MessageCenterManager : NSObject

         @property (nonatomic ,assign) NSInteger messageType;
         + (instancetype)sharedInstance;
         @end
       
        .m实现
         #import "MessageCenterManager.h"
         static MessageCenterManager *_sharedInstance;
         @implementation MessageCenterManager
         + (instancetype)sharedInstance{
              static dispatch_once_t onceToken;
             dispatch_once(&onceToken, ^{
                      _sharedInstance = [[MessageCenterManager alloc] init];
             });
             return _sharedInstance;
         }

         -(id)copyWithZone:(NSZone *)zone{
             return _sharedInstance;
         }

         +(id)allocWithZone:(struct _NSZone *)zone{
                static dispatch_once_t onceToken;
                        dispatch_once(&onceToken, ^{
                            _sharedInstance = [super allocWithZone:zone];
                         });
               return _sharedInstance;
         }
        @end

此时我们创建了一个单例,且看下边的用法,是错误的,不安全的。

       #import "UserMessage.h"
       @implementation UserMessage
       - (void)someMethod{
      //在这里是不能像这样引用单例的,这样的话用户消息和广播消息就会耦合在一起
        if([MessageCenterManager sharedInstance].messageType){
              //do something
        }else{
        }
       }
       @end

       #广播消息中
        @implementation BroadcastMessage
         - (void)someMethod{
                [[MessageCenterManager sharedInstance] setMessageType:0];
          }
        @end

重要的事情加警告

上一篇 下一篇

猜你喜欢

热点阅读