Re: literal strings - who do they belong to?
Re: literal strings - who do they belong to?
- Subject: Re: literal strings - who do they belong to?
- From: Wade Tregaskis <email@hidden>
- Date: Mon, 13 Jul 2009 19:57:04 -0700
id obj = [dict objectForKey:@"whatever"];
[dict release];
NSLog( @"this will crash %@", id );
And if you extrapolate this example further to the case where [dict
release] is called on another thread, you're in a real pickle.
Ideally, objectForKey: would retain]autorelease].
This multithreading argument is completely irrelevant. If your code
is not thread safe, that is a completely independent issue which
atomic and retain/autorelease will not solve!
Fair to say. I contemplated expanding on this point previously, but
declined by way of laziness. You sods proffer no mercy, do you? :P
Atomic properties (nor autorelease pools) are definitely not a panacea
for multithreading.
That said, bear in mind what my suggestion does buy you: if
NSDictionary did atomically retain]autorelease] from objectForKey:,
then it would be thread-safe to mutate the dictionary. If this is
just some big global, say - some kind of cache or hash table or
whatever else - it may well be a totally appropriate level to
implement that thread safety.
If, however, as Peter points out, it's just some little dictionary
buried in some bigger class, then it's likely not the level you want
to resolve mutual exclusion at. But it doesn't necessarily hurt;
maybe your app will still draw things out of order, but at least it
doesn't crash.
Furthermore, in the example above 'dict' should be owned by the
execution function at that time, since it's either explicitly owned,
or was returned to it via retain]autorelease]. See how it recurses?
If everyone plays by these rules, life gets a whole lot simpler.
Keep in mind the dictionary case is just an example, not to be taken
too literally for the purposes of this discussion.
The warning I've tempered this advice with throughout is with regards
to performance. We all cut corners sometimes in the name of necessary
practicality. Otherwise we'd all be programming in Lisp instead of
this clumsy C stuff. And you should have seen some of the internal
discussions over whether @property should be atomic by default or
not. But the performance mantra applies as always: correct first,
optimal later (though, please, not too much later :) ).
Wade
_______________________________________________
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