单例、单例模式

来源:互联网 发布:惠阳区网络问政 编辑:程序博客网 时间:2024/04/28 10:18
简单的实现一个单例:
  1. (instancetype)sharedInstance  
  2.         static MyClass *_instance nil;  
  3.         static dispatch_once_t predicate;  
  4.         dispatch_once(&predicate, ^{  
  5.                 _instance [[MyClass alloc] init];   
  6.         });

  7.     return _instance 


真正的单例模式:
+ (MyClass *)sharedInstance  // 第二步:实例构造检查静态实例是否为nil
    static MyClass *_instance nil; 
    @synchronized (self) {
      if (!_instance) {
            _instance = [[super allocWithZone:NULL] init];
      }
    }
   
   return _instance;
}

+ (id)allocWithZone:(NSZone *)zone { // 第三步:重写allocWithZone方法
      if (!_instance) {
_instance= [[MyClass alloc] init];
  return_instance;
     }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone{ // 第四步
    return self;
}

// 以下只在MRC下才需要写,因为在ARC下不让调用一下方法,所以不用担心引用计数的问题。
- (id)retain {
    return self;
}

- (NSUInteger)retainCount {
    return NSUIntegerMAX;
}

- (void)release {  
}

- (id)autorelease {
    return self;
}

0 1