Re: Creating Shared Named Objects
Re: Creating Shared Named Objects
- Subject: Re: Creating Shared Named Objects
- From: "Michael Ash" <email@hidden>
- Date: Mon, 12 Jun 2006 23:20:46 -0400
On 6/12/06, Steve Sheets <email@hidden> wrote:
Just another design question...
I want to create a custom class that reads data from inside the
bundle (XML data, strings & images). The class is complex (ie. single
object that hold other objects and collection of objects). Besides
other fields, objects of the class will be named, similar to the way
Sound and Images can be named.
Thus I want to have a creation class call that will return the object
for a given name:
+ (MyObject*) namedMyObject:(NSString*)p_name;
This object would check to see if that named object has already been
loaded in, if so, it returns the already loaded object. If not, it
loads the object into memory (if possible), and returns it. If two
locations in my code call this routine with same name, only a single
object would have been created, and returned to both instances of the
calls.
Obviously I need to store the created objects into some global
collection (array or dictionary) so that when I ask for given object
with given name, I can check previously created objects before
creating a new one.
Here is the problem. How do I handle releasing the object?
Use a dictionary which does not retain its values. You can construct
such a beast using CFDictionary, or by indirecting through NSValue for
the values rather than storing the objects directly. Then have your
objects be aware of the dictionary, and remove themselves from it in
their dealloc method.
This should ensure decent behavior for your situation. Objects get
created and stored in the dictionary. So long as somebody still holds
a reference to them, new requests for an object will get the same one.
When all references to the object go away, it's destroyed and removed
from the dictionary.
Be careful to have your accessor do a retain/autorelease dance, or do
such a dance explicitly in the calling code (I recommend the former
since having it in one place is almost always better), since otherwise
you could have pointers "spontaneously" going bad on you just because
you released an apparently unrelated object.
Mike
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden