Re: KVO query
Re: KVO query
- Subject: Re: KVO query
- From: Ken Thomases <email@hidden>
- Date: Wed, 13 Aug 2014 17:40:30 -0500
On Aug 13, 2014, at 4:53 PM, Jonathan Mitchell <email@hidden> wrote:
> I have a key path like so which is observed:
>
> submission.status.name
>
> At one point i need to invoke a manual KVO notification like so:
>
> [submission willChangeValueForKey:@“status”];
> [submission didChangeValueForKey:@“status”];
>
> This raises like so:
>
> Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot update for observer <NSKeyValueObservance 0x608000ac21b0> for the key path "status.name" from <Submission 0x6080003aa800>, most likely because the value for the key "status" has changed without an appropriate KVO notification being sent. Check the KVO-compliance of the Submission class.’
>
> I am using manual KVO because my submission object is a wrapper around a Mono managed class.
> I receive a callback that the managed status object has changed and want to propagate that via KVO.
> The true situation is generic : i receive a callback that a managed property P has changed and want to raise manual KVO notifications in a compliant manner.
>
> Is there a way for me to programatically determine what sequence of manual KVO notifications I will require to maintain KVO compliance?
You have to issue the -willChange… _before_ the property has changed. That's because that's KVO's only opportunity to get the value that's about to become "old" and remove its observations for the properties of that old object.
So, that pattern of issuing -willChange… followed immediately by -didChange… with nothing actually changing in between is a sure sign of a problem.
The solution is annoying but relatively simple. You need to hold a strong reference to the old object in a property of your own. So, you need a property "status" that is _not_ just a pass-through to some other API. It needs to be backed by an instance variable (e.g. _status) that is a strong reference to the object. Then, when you receive the notification from the underlying API that something has changed, you fetch the new object from that API and assign it to self.status. That assignment is KVO-compliant. You can/should then eliminate your manual -will/didChange… invocations.
Regards,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
References: | |
| >KVO query (From: Jonathan Mitchell <email@hidden>) |