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(@"======");
}];
}