单例设计模式

在objective-c中要实现一个单例类,至少需要做以下四个步骤:
  1、为单例对象实现一个静态实例,并初始化,然后设置成nil,
  2、实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例,
  3、重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实力的时候不产生一个新实例,

  4、适当实现allocWitheZone,copyWithZone,release和autorelease。

@interface single : NSObject

+(id)shareInstance;

-(NSString *)sendValue;

@property (nonatomic , copy)NSString *userName;

@end



#import "single.h"

static single *shareInstance = nil;//第一步:静态实例,并初始化。

@implementation single

+(id)shareInstance{//第二步:实例构造检查静态实例是否为nil

    if (shareInstance == nil) {

        shareInstance = [[[self class] alloc]init];

    }

    return shareInstance;

}

-(NSString *)sendValue{//实例方法的实现

    NSString *str = @"abc";

    return str;

}

+ (id) allocWithZone:(NSZone *)zone //第三步:重写allocWithZone方法

{

    @synchronized (self) {

        if (shareInstance == nil) {

            shareInstance = [super allocWithZone:zone];

            return shareInstance;

        }

    }

    return nil;

}


- (id) copyWithZone:(NSZone *)zone //第四步

{

    return self;

}

@end


#import "ViewController.h"

#import "NextViewController.h"

#import "single.h"



@interface ViewController ()


- (IBAction)buttonClick:(id)sender;


@end


@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

//    self.sendValue.text =

      self.sendValue.text =  (NSString *)[[single shareInstance]sendValue];//取出单例并调用该单例中的实例方法(返回自己定义的对象)

}

- (IBAction)buttonClick:(id)sender {

    

    NextViewController *nextVC = [[NextViewController alloc]initWithNibName:@"NextViewController" bundle:nil];

    [self presentViewController:nextVC animated:YES completion:^{

        NSLog(@"======");

    }];

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值