Daniel Luis dos Santos wrote:
Hello,

I have a shared library and some client code. In the shared library I am adopting the following method signature pattern :

- (int) someMethod: (aType*)someInParam anotherParam: (aType**)someOutParam;

I use the return value to indicate success or failure in the execution of the method, and the arguments to pass parameters in and out.
The out parameters are double pointers.

Also, the pattern I am using mandates that the out parameters dereferenced values are allocated within the method. So :

- (int) someMethod: (aType*)someInParam anotherParam: (aType**)someOutParam {

    *aType = [[aType alloc] init];

    return 0;
}

would do some logic and allocate the return value and set it to the double pointer, that would be the visible on the calling scope.

My problem is that I am not really sure of the way Cocoa retains and releases objects. Using a global auto release-pool, when is the out param object released ? At the end of the scope of someMethod ? or when I explicitly release it ? If the former, I have to retain it withing some method so that when its scope finishes the ref count doesn't go to zero right ?

Doing it with [[aType alloc] init] as you are in your example, the return type is never released unless explicitly released by the caller.




Since the idea is to continue using the return type throughout the enclosing method call's scope how do I implement this safely so that I don't end up trying to access release memory ?


A good example to follow here is what is done with the NSError **s used in many Cocoa methods. These are typically returned after having autorelease called on them, so by changing your code above to

[[aType alloc] init] autorelease]

You should be all right as long as you do not do the above inside an autorelease pool created in your own function.

If your caller is interested in keeping the value around longer than the scope of the calling method, or the current autorelease pool, then the caller can always explicitly -retain the returned object.

Even though you are basing the functionality on a common Cocoa idiom, it is a good idea to document that the method will return an autoreleased object in the pointer. This way, your client methods can be coded appropriately.


Jason


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to