我正在阅读关于KVO
的教程,示例显示当我们不使用KVO样式时值不会更新,所以我想知道:为什么,如果对象是通过“引用”传递的(使用id
或Position*
),所以如果我们使用指向“anObject”的指针,那么值(来自对象)是不是会更新?
所以这里是代码:在“main”中:
// Create initial position
Position* pos = [[Position alloc] init];
pos.latitude = 45.0;
pos.longitude = 12.0;
pos.altitude = 30.0;
// Create a basic tracker
ValueTracker * tracker = [ValueTracker createValueTrackerForKey:@"latitude" onObject:pos];
// Dump initial state
NSLog(@"Tracker (1): %@", tracker);
pos.latitude += 5.0;
pos.longitude += 5.0;
pos.altitude += 10.0;
NSLog(@"Tracker (2): %@", tracker); //the values are not updated
对象:
@interface Position : NSObject {
float latitude;
float longitude;
float altitude;
}
@property(assign, readwrite) float latitude;
@property(assign, readwrite) float longitude;
@property(assign, readwrite) float altitude;
和函数:这里,anObject
是指向Position
的指针,为什么不能使用指针更新值?
+ (ValueTracker *) createValueTrackerForKey: (NSString *) aKey
onObject: (id) anObject
{
ValueTracker * tracker = [[ValueTracker alloc] init];
tracker.valueKey = aKey;
tracker.source = anObject;
tracker.value = [anObject valueForKey: tracker.valueKey];
return tracker;
}
编辑:这是我们使用kvo系统的时候:
[tracker enableObserving];
并在ValueTracker类中:
- (void) enableObserving
{
if ( nil != source ) {
/* We specify in options that we want to get both old and new value
for the property.
*/
[source addObserver: self
forKeyPath: valueKey
options:(NSKeyValueObservingOptionNew |
NSKeyValueObservingOptionOld)
context: NULL];
}
}
编辑n°2:
- (void) observeValueForKeyPath: (NSString *) keyPath
ofObject: (id) object
change: (NSDictionary *) change
context: (void *) context
{
NSLog(@"Value %@ changed! Here is the changeset: %@", keyPath, change);
//NSLog(@"Dump on observation: %@", [self description]);
value = [change valueForKey:NSKeyValueChangeNewKey];
}
答案 0 :(得分:0)
看起来你忘了合成你的iVars了吗?
@implementation Position
@synthesize latitude, longitude, altitude;
...
@end