-(id) init {// 标准初始化模板self = [super init];if (self) {// 实例变量初始化}return self ;}
@interface Person : NSObject// 定义属性@property(nonatomic) NSString *name ;@property(nonatomic) NSInteger age ;// 覆盖父类的初始化方法-(id) init ;// 初始化所有属性-(id) initWithName : (NSString *) newName andAge : (NSInteger) newAge ;@end@implementation Person// 合成getter、setter方法@synthesize name ,age ;// 初始化方法,调用其他初始化方法-(id) init {return [self initWithName:@"张三" andAge: 13 ] ;}// 初始化所有参数方法-(id) initWithName:(NSString *)newName andAge:(NSInteger) newAge {// 初始化父类self = [super init ];if (self){self.name = newName ;self.age = newAge ;}return self ;}@end
所谓单例,即我们自己创建一个单例类,该类只能生成唯一的对象,为了防止该对象被复制(copy)或者retain 和 release 等操作,我们必须在所创建的单例的实现文件( .m 文件)中将父类的这些方法给覆盖,该目的是为了保证单例模式的一个严谨性。
注意实现NSCoping协议
@implementation Person// 获得对象的唯一入口+(Person *)shareInstance{// 静态对象引用static Person *shareInstance=nil;// 检查唯一实例是否创建if (shareInstance == nil) {// 创建对象,这里使用super 的 allocWithZone ,是因为要调用 父类(NSObject) 的 allocWithZone 进行底层内存分配.shareInstance = [[super allocWithZone:NULL] init ];}return shareInstance;}// 覆盖NSObject方法+(id)allocWithZone:(NSZone *)zone{return [self shareInstance];}// copy 的时候返回自身-(id)copyWithZone:(NSZone *)zone{return self;}
@implementation Person// 获得对象的唯一入口+(Person *)shareInstance{// 静态对象引用static Person *shareInstance=nil;// 检查唯一实例是否创建if (shareInstance == nil) {// 创建对象,这里使用super 的 allocWithZone ,是因为要调用 父类(NSObject) 的 allocWithZone 进行底层内存分配.shareInstance = [[super allocWithZone:NULL] init ];}return shareInstance;}// 覆盖NSObject方法+(id)allocWithZone:(NSZone *)zone{//retainreturn [self shareInstance];}// copy 的时候返回自身-(id)copyWithZone:(NSZone *)zone{return self;}-(id)retain{return self;}//无穷大的数,表示不能释放-(NSUInteger)retainCount{return NSUIntegerMax;}-(oneway void)release{//什么也不做}-(id)autorelease{return self;}@end
原文:http://www.cnblogs.com/mrwu/p/4331148.html