Reputation: 31
For example ;
TheClass * aInstance = [[TheClass alloc] init];
TheClass * bInstance;
bInstance = aInstance;
[bInstance release]
Would the memory allocated by aInstance be freed in this case?
Upvotes: 3
Views: 87
Reputation: 2953
Yes. You only initialized it once, and only released it once. So the retain count is 0.
The rules are:
Upvotes: 0
Reputation: 243156
Yes.
It sounds like you're a bit confused about what's going on, so I'll explain a couple things:
aInstance
. That's simply a spot in memory that holds a number. The memory was actually allocated by the TheClass
class.aInstance
simply holds that location (which is a big number). That's it. This number is interpreted as a pointer (ie, a reference to another location in memory), but it doesn't have to be. You could use it as an int, if you're feeling adventurous. bInstance = aInstance;
, you're simply copying that number from one memory slot to another. You're not doing anything to the object reference by that variable. You're just duplicating an already existing pointer. nil
to them). Whew, that's a lot of typing for an iPhone keyboard. :P
Upvotes: 2
Reputation: 582
Yes it will be freed.
If u replace "bInstance = aInstance;" with:
bInstance = [aInstance retain];
it will not free the memory until you release it one more time. Though you might want to use autorelease for short term usage.
Upvotes: 0
Reputation: 535
TheClass * aInstance = [[TheClass alloc] init]; //retain count = 1
TheClass * bInstance; //this is a pointer so retain count remain 1
bInstance = aInstance; //the pointer refer to the instance (retain count =1)
[bInstance release] //release => retain count =0, object released
Upvotes: 0
Reputation: 181340
Yes, it would be freed and neither aInstance
not bInstance
should be used safely after the release.
Upvotes: 0
Reputation: 71038
Yes, it would be, because there's only one instance-- you just have two different pointers to it.
As in plain C, the assignment of the address (the pointer) for some object to different variables has no bearing on the actual memory allocation used for that object. In Objective-C, the same concept applies. If you want to "keep" two different references to one object, you'll need to have both references "own" it. In this case, that would be by having the second reference retain
the object, likely because you're storing it in an instance variable, etc.
Upvotes: 2