Re: storage for context: value
Re: storage for context: value
- Subject: Re: storage for context: value
- From: Quincey Morris <email@hidden>
- Date: Thu, 25 Jul 2013 09:19:33 -0700
On Jul 25, 2013, at 07:20 , Matt Neuburg <email@hidden> wrote:
> storage of the value passed as context:(void*), not just in addObserver:, but in general
I think I'd take this in a different direction. In *all* of these scenarios the context parameter is a mechanism for passing a pointer to a data structure to a callback/completion routine/handler with a generic signature, as Roland already said.
That leads to a set of potential pitfalls:
-- Memory management. If the data structure is allocated memory (C idiom) or an object (ObjC idiom), it's not trivial to manage its lifetime.
-- Heterogeneity. If contexts of different idioms are fed to the same handler, it can be difficult to decide what data structure is being pointed to.
-- Complexity. If the data structure pointed to is just a single value (such as a simple type, or a simple identifier), it can take a lot of code to package this in a real data structure that behaves properly wrt the first 2 pitfalls.
The 'static void* x = &x;' convention you mention (a "pointer as tag" convention) is significant only because it's a very elegant way to avoid all 3 pitfalls, when no additional data needs to be passed. It also has the virtue of relieving the developer from the need to remember whether to put a '&' on the front of the argument.
The story behind 'addObserver' (or, really, the story behind 'observeValueForKeyPath') is a separate matter. This particular API was misdesigned, because it did not properly envisage a need to identify multiple observations of the same thing. Thus, the 'context' parameter came to be used as this identification -- there was no actual data structure to be passed in. The above "pointer as tag" convention bubbled to the top of the pile as the most convenient way to solve the problem.
_______________________________________________
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