iOS observeValueForKeyPath not getting called
I had a problem getting observeValueForKeyPath to be called but solved it using this:
observeValueForKeyPath not being called
However, I'd like to know how to handle this in general for future reference.
The code that works looks like this:
- (void) input: (NSString*) digit
{
NSLog(@"input() - Entering... digit=%@", digit);
if ([digits length] < MAX_DIGITS_LENGTH)
开发者_JAVA百科 {
self.digits = [[[ self.digits autorelease] stringByAppendingString:digit] retain];
NSLog(@"digits is now %@", digits);
}
}
Prior to this I was using an NSMutableString instead of NSString and just said used appendString. I didn't do an assignment and I wasn't appending "self" to the digits variable. Are there any good websites/tutorials that explain this more in depth so I know how to do this in general for any type of object?
KVO works by method swizzling and notifying on value changes. If you access your properties with out self then you are accessing an iVar directly and not using the method. When not using a method there is no way to send KVO notifications to your observer. The other issue you ran into is mutable vs immutable data. When you are appending a string you not changing the object but you are changing the data it is pointing at and that is why you were not getting any notifications. Only the get accessor was being called to get the string then you were calling append data on that.
Your memory mgmt seems off. Assuming 'digits' is a @property declared with the retain or copy attribute, and you are using the synthesized setter (or wrote an equivalent one yourself), then you should use the setter like this:
self.digits = [self.digits stringByAppendingString:digit];
You shouldn't autorelease the old value or retain the new one, since the setter does that for you.
If you would like to use an NSMutableString there instead, you could trigger the KVO notifications manually like so:
[self willChangeValueForKey:@"digits"];
[self.digits appendString:whatever]; // assumes digits is a mutable string now
[self didChangeValueForKey:@"digits"];
Hope that helps.
精彩评论