OC中的单例模式和委托模式

来源:互联网 发布:人工智能的公司有哪些 编辑:程序博客网 时间:2024/06/16 03:27

单例模式是设计模式的一种,主要的作用是用于设计约束或者为了控制对有限资源的访问

首先新建一个类,在类中添加单例

+ ( 类名)方法名(通常share,defluat等开头);


在.m文件中创建全局静态实例

static 类名 *st = nil;   赋值nil

+ (类名)方法名{


if(st==nil){


  st = [[类名 alloc] init];

}

  return st;

}


+ (id)allocWithZone :(NSZone *)zone{

@synchronized{

    if(st == nil){

        st = [super allocWith: zone ];

   }

    return st;

 

.h文件导入NSCopying协议

- (id)copyWithZone :(NSZone *)zone{

 return self;

}

然后在主文件实现


2.委托模式

委托模式不使用协议或者类目也可以实现

用来传输数据





0 0
原创粉丝点击