Copy, kvc, and kvo in iOS
There are two methods to copy an object.
Copy: returns an immutable copy.
Only NSString to NSString must be copied in shortest mode, and others must be in deep copy mode. Deep copy object: Specifies the shortest copy pointer. MutableCopy: Steps to copy a normal object of a mutable copy
Compliance with the NSCopying Protocol
# Import
@ Interface MRCar: NSObject
/** Price */@ property (nonatomic, assign) double price;/** weight */@ property (nonatomic, assign) double weight; @ end
-Implementation-copyWithZone: method-create a new object-assign a value to the attribute of the new object
#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
KVC Full name: Key Value Coding (Key Value encoding) Value assignment
// Modify the private member variable-(void) setValue :( id) value forKey :( NSString *) key;-(void) setValue :( id) value forKeyPath :( NSString *) keyPath; -(void) setValuesForKeysWithDictionary :( NSDictionary *) keyedValues;
Value
// Obtain the value of the Private member variable-(id) valueForKey :( NSString *) key;-(id) valueForKeyPath :( NSString *) keyPath;-(NSDictionary *) dictionaryWithValuesForKeys :( NSArray *) keys;
KVO Full name: Key Value Observing
Add listener
// Add an Observer (listener) to object a // Observer: Listener // KeyPath: attribute name (which attribute needs to be monitored) [a addObserver: B forKeyPath: @ name options: NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context: @ test];
-Listener Method
/*** When the attribute value of an object monitored by KVO is changed, it will automatically call this ** @ param keyPath, which attribute is changed * @ param object, and the attribute of which object is changed * @ param change to the format * @ param context when addObserver context parameter value */-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {NSLog (%%@%@, object, keyPath, change, context );}