views:

80

answers:

2

I am just getting started with cocoa. So please excuse the silly question, but I can't quite wrap my head around some aspects of memory management yet.

In the interface of my class I am declaring an object as CEMyObjectclass *myObject;. I do not alloc or init the obect in the classe's init menthod. But I do have a method that calls myObject = [[CEMyObjectclass alloc] initWithImage:someImage];. Will that eventually run out of memory or does myObject just get overwritten by a new instance every time that method is called?

Thanks!

+1  A: 

You should eventually run out.

Remember that myObject is just a pointer to a block of memory. The pointer myObject will be pointing to the newly allocated object, and you'll have no reference to the old one. Therefore, you won't be able to release its memory (but the object will still be around).

In general, if you alloc something (or retain it), you are responsible for matching this message with a release somewhere later.

vicvicvic
The garbage collector won't clean this up?
Bryan
As far as I know, there is no garbage collector on the iPhone.
vicvicvic
When an app exits entirely... is 'leaked memory' still leaked?
Bonnie
I'm no expert, but I'd say generally (in practically all cases) no. The OS will clean up after your app once it exits -- it's part of its responsibility to keep the system stable (even in the face of "leaking" apps).
vicvicvic
A: 

Thanks for the answer. So in this case, would I just call [myObject release]; before the myObject = [[CEMyObjectclass alloc] initWithImage:someImage];?

cbarlo
Yeah, precisely. If you're going to "recycle pointers", you need to make sure that your old object is released first.
vicvicvic
I still can not get this to work... [myObject release]; = [[CEMyObjectclass alloc] initWithImage:someImage]; crashes with EXC_BAD_ACCESS...
cbarlo
Are you sure that `someImage` is initialized?In general, you would not be programming in this fashion. Since your question was a "newbie" question, I'm thinking you might be doing something else backwards.
vicvicvic