Copy
- There are 2 ways to implement a copy
- Copy: Returns an immutable copy
- Only nsstring to nsstring copy is a shallow copy, the others are deep copy. Deep copy Copy object, shallow copy copy pointer.
- Mutablecopy: Returns a mutable copy
- Steps to implement a copy of a normal object
- Compliance with Nscopying Protocol
#import <Foundation/Foundation.h>@interface MRCar : NSObject <NSCopying>/** 价钱 */@propertydouble price;/** 重量 */@propertydouble weight;@end
- 实现-copyWithZone:方法 - 创建新对象 - 给新对象的属性赋值
#import "MRCar.h"@implementation MRCar- (id)copyWithZone:(NSZone *)zone{ MRCar *copyCar = [[MRCar allocWithZone:zone] init]; copyCar.priceself.price; copyCar.weightself.weight; return copyCar;}@end
KVC
- Full Name: Key value Coding (key code)
- Assign value
// 能修改私有成员变量- (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;
KVO
- Full Name: Key value observing (key monitoring)
- Role: Changes in the property values of the listener model
- Steps
// 为对象a添加一个观察者(监听器) // Observer:观察者(监听器) // KeyPath:属性名(需要监听哪个属性) [a addObserver:b forKeyPath:@"name"| 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); }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Copy in iOS, KVC,KVO