#import <Foundation/Foundation.h>
@interface MRCar : NSObject <NSCopying>
/** 价钱 */
@property (nonatomic, assign) double price;
/** 重量 */
@property (nonatomic, assign) double weight;
@end
- 实现-copyWithZone:方法
- 创建新对象
- 给新对象的属性赋值
#import "MRCar.h"
@implementation MRCar
- (id)copyWithZone:(NSZone *)zone
{
MRCar *copyCar = [[MRCar allocWithZone:zone] init];
copyCar.price = self.price;
copyCar.weight = self.weight;
return copyCar;
}
@end
// 能修改私有成员变量
- (void)setValue:(id)value forKey:(NSString *)key;
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues;
// 能取得私有成员变量的值
- (id)valueForKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
- (NSDictionary *)dictionaryWithValuesForKeys:(NSArray *)keys;
// 为对象a添加一个观察者(监听器)
// Observer:观察者(监听器)
// KeyPath:属性名(需要监听哪个属性)
[a addObserver:b forKeyPath:@"name" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:@"test"];
- 在监听器中实现监听方法
/**
* 当利用KVO监听到某个对象的属性值发生了改变,就会自动调用这个
*
* @param keyPath 哪个属性被改了
* @param object 哪个对象的属性被改了
* @param change 改成咋样
* @param context 当初addObserver时的context参数值
*/
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@ %@ %@ %@", object, keyPath, change, context);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/supersonico/article/details/46835961