OC进阶(六)

1.Copy

/*
   自定义类实现copy的功能:
 
   1) 创建一个类
 
   2) 遵守NSCopying协议
 
   3) 实现协议中声明的方法
 
   4) [对象 copy];
 
 
      目的:  产生一个副本对象
 */
#import <Foundation/Foundation.h>

@interface Dog : NSObject<NSCopying>
@property (nonatomic,assign) int tuiNum;
@property (nonatomic,assign) int speed;
@end
@implementation Dog
- (id)copyWithZone:(NSZone *)zone{

    NSLog(@"执行了copy方法");
    
    //
    Dog *d = [[Dog alloc] init];
    //new speed   jd speed
    d.speed = self.speed;
    d.tuiNum = self.tuiNum;

    return d;
}
@end
#import "Dog.h"
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
       
        Dog *jd = [Dog new];
        jd.speed = 230;
        jd.tuiNum = 8;
        //对象的copy
        //自定义对象的copy都是深拷贝
        Dog *byd= [jd copy];
        //byd.speed = 230
        //byd.tuiNum = 8
        NSLog(@"%d,%d",byd.speed,byd.tuiNum);
        
    }
    return 0;
}

2.单例模式

/*
 
     单例模式:
 
         对象在任何时候,都只有一个,好处是,在多个类之间共享数据
 
     设计要点:
 
         1) 保证唯一,程序运行期间必须唯一
         2) 单例类,必须提供一个接入点(特殊的类方法)
         
 */
#import <Foundation/Foundation.h>

@interface SingletonTools : NSObject<NSCopying>
@property (nonatomic,assign) int num;
@property (nonatomic,copy) NSString *text;

//单例的类,提供一个接入点
+(instancetype)shareInstances;
@end
#import "SingletonTools.h"

//定义一个全局变量
static SingletonTools *instances = nil;

@implementation SingletonTools
-(id)copyWithZone:(NSZone*)zone{

    return self;
}
+(id)allocWithZone:(NSZone*)zone{

    //线程保护
    @synchronized(self) {
        
        if (instances == nil) {
            //调用父类的alloc
            instances = [super allocWithZone:zone];
            
            return instances;
        }
        
    }
     return instances;

}
-(id)retain{

    return self;

}
-(NSUInteger)retainCount{

    return NSUIntegerMax;
}
-(oneway void)release{
 

}
-(id)autorelease{

    return self;

}
//单例的接入点方法
+(instancetype)shareInstances{

    //目的:保证对象必须唯一
    if(instances == nil){
        
        //创建一个对象
        instances = [[SingletonTools alloc] init];
        return instances;
    
    }

    return instances;

}
@end

 

posted @ 2015-10-29 15:38  ios开发那点事  阅读(191)  评论(0编辑  收藏  举报