#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
@interface SingleTonBase : NSObject
@property (copy,readwrite) NSString* MyName;
+(instancetype)SharedInstance;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
SingleTonBase* m1 = [SingleTonBase SharedInstance];/*SharedInstance->init*/
SingleTonBase* m2 = [[SingleTonBase alloc] init]; /*allocWithZone->SharedInstance->init->init*/
SingleTonBase* m3 = [m2 copy]; /*copy*/
SingleTonBase* m4 = [SingleTonBase alloc]; /*allocWithZone->SharedInstance->init*/
SingleTonBase* m5 = [SingleTonBase new]; /*allocWithZone->SharedInstance->init->init*/
SingleTonBase* m6 = [m2 mutableCopy]; /*mutableCopy*/
/*能编译,但访问成员变量的时候,崩溃。
SingleTonBase* m7 = [SingleTonBase copy];*/
NSLog(@"%p,%p,%p,%p,%p,%p",m1,m2,m3,m4,m5,m6);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
static SingleTonBase* Instance = nil;
@implementation SingleTonBase
{
}
-(instancetype)init
{
if (Instance) {
return Instance;
}
if (self = [super init]) {
self.MyName = @"default name";
}
return self;
}
+(instancetype)SharedInstance
{
static dispatch_once_t one;
dispatch_once(&one, ^{
Instance = [[super allocWithZone:nil]init];
});
return Instance;
}
+(id)allocWithZone:(struct _NSZone *)zone
{
return [self SharedInstance];
}
-(id)copy
{
return self;
}
-(id)mutableCopy
{
return self;
}
@end
总结下:
1,实现起来比c++要复杂,考虑的情况挺多,这个写法貌似是官方提供的。
2,非arc模式没有考虑
3,好像不能像c++声明静态的类成员变量。
参考:http://blog.csdn.net/a451493485/article/details/8624990