Re: Leaking Memory
Re: Leaking Memory
- Subject: Re: Leaking Memory
- From: David Cairns <email@hidden>
- Date: Mon, 20 Jan 2003 19:19:38 -0500
I am also a bit of a newbie myself (programming in cocoa since 09/02).
Memory management is the hardest part of programming in Cocoa IMHO.
Anyhoo, there are few _really really_ important points of dealing with
memory allocation/ deallocation in cocoa. Since none of the articles
that I have read have stated this very clearly, I'll give you a few
examples myself. But first let me explain a few of the basic methods...
alloc -- allocates memory for an object
init -- initializes the data members of an object
release -- deallocates an object _right away_
autorelease -- deallocates an object when you don't need it anymore
(generally at the end of whatever method the autorelease is declared)
therefore, to create a new object myObject of class MyClass, you would
see something like this:
MyClass *myObject;
myObject = [[MyClass alloc] init];
or
MyClass *myObject;
myObject = [[MyClass alloc] initWithStuff: stuff];
note that both of those examples can be shortened to MyClass *myObject
= ... just like any other variable in C.
one of the trickier (ie "less documented") common cocoa practices are
called "convience constructors." They are commonly labeled as
"objectWithStuff:" instead of just "initWithStuff:". Note that these
do not require an alloc statement because they do that stuff
themselves. Also note that such constructors are sent directly to the
class itself. Here you go:
MyClass *myObject = [MyClass objectWithStuff: stuff];
Anyhoo, normally when you create an object you later have to either
release it or autorelease it (generally depending on whether you are
sure or not that it will later be used. For example:
MyClass *myObject = [[MyClass alloc] init];
[myObject release];
The important thing to remember about convience constructors is that
the objects they return are _already autoreleased_. That means that if
you try to send a release or autorelease to an object created with a
convience constructor you will either get a signal 10 (SIGBUS) or 11
(SIGSEGV) error, which is of course, bad. Here's an example:
MyClass *myObject = [MyClass objectWithStuff: stuff];
there you go. that's all. DON'T TRY TO [myObject release] WHATEVER
YOU DO!
well, that's my little crash-course in cocoa memory management. If you
need any help or are getting SIGBUS or SIGSEGV errors, let me know; I'm
always happy to help out another 'n00B.'
-- dave
--------------------------------------------
"see you later, space cowboy..."
--------------------------------------------
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.