Re: Objective-C vs. Java
Re: Objective-C vs. Java
- Subject: Re: Objective-C vs. Java
- From: Jim Correia <email@hidden>
- Date: Wed, 25 Jul 2001 20:57:32 -0400
On 8:17 PM 7/25/01 Art Isbell <email@hidden> wrote:
>
On Wednesday, July 25, 2001, at 02:02 PM, Mike Shields wrote:
>
>
> The one thing I'm looking for is Stack-based objects so I can use
>
> scoping to automatically cleanup allocated resources (memory, open
>
> files, etc). It's the one thing I miss from C++ (other than
>
> variables anywhere, but you can get around that pretty easily with
>
> brackets)
>
>
You won't be finding them in Objective-C even after the ObjC++
>
compiler is available. Autoreleased Objective-C objects are almost
>
equivalent to stack objects in that they are automatically
>
deallocated.
Almost equivalent is not good enough for the kind of objects I think
Mike is talking about.
Suppose you have a class called ColorRestorer.
The constructor remembers the existing color, and sets the color to the
new value. The destructor sets the color to the saved color.
In C++
function_one()
{
ColorRestorer saveAndRestoreColor(red);
draw_a_string(); // draws in red
function_two();
draw_a_string(); // draws in red
}
function_two()
{
ColorRestorer saveAndRestoreColor(blue);
draw_a_string(); // draws in blue
}
In objective-c with autoreleased objects
function_one()
{
ColorRestorer *saveAndRestoreColor = [[ColorRestorer
initAndSetToColor: red] autorelease];
draw_a_string(); // draws in red
function_two();
draw_a_string(); // draws in blue because both auto-released objects
do their work in the dealloc method, which won't be called until later
}
function_two()
{
ColorRestorer *saveAndRestoreColor = [[ColorRestorer
initAndSetToColor: blue] autorelease];
draw_a_string(); // draws in blue
}
I'm new to objective-C, so there may be a way to do this. But your one
liner utility object to save the state and restore it when it goes out
of scope has to become a manual release in objective-c unless I've
missed something.
ColorRestorer *saveAndRestoreColor = [ColorRestorer initAndSetToColor:
blue];
draw_a_string();
[saveAndRestoreColor release];
It isn't the end of the world, but removes the convenience of the stack
based utility objects such that for the simplest cases, they probably
aren't even worth having.
For things where you just want the resources that you've allocated to be
cleaned up, and the next time through the event loop is soon enough, and
you don't care about the order of destruction, or whether it happens as
the stack is unwound, autorelease is quite nice when used in appropriate
situations.
Jim