Question

I have a question regarding memory management in Objective C.

Here is the code...

SomeObject * objectA;
SomeObject * objectB;

objectA = [[SomeObject alloc] init];

objectB = objectA;

From a memory perspective, is object B an autorelease object? Is it weak/strong? Is it simply pointing to object A and will become nil if object A is released?

Was it helpful?

Solution

Both objectA and objectB will have a strong reference, so if they're both pointing to the same object, then it won't be deallocated until either both of them are set to nil or they both go out of scope. This is of course assuming ARC is enabled. If ARC isn't enabled, then your object will only be deallocated if you call release on it.

Now, under ARC, if you wanted only one of them to have a strong reference to the object, then you could put the __weak qualifier in front of one of the variables. Of course in your example, if you make objectA weak, then it will result in your object being deallocated immediately, so both of your pointers will remain nil.

OTHER TIPS

Assuming that ARC is enabled, and objectA and objectB are local variables, then they both act as strong pointers. So setting objectA to nil has no effect on objectB or the underlying object. Setting objectA and objectB to nil will release the underlying object. Also when objectA and objectB go out of scope, the underlying object will be released.

This code

@interface SomeClass : NSObject
@end

@implementation SomeClass
- (void)dealloc
{
    NSLog( @"dealloc underlying object" );
}
@end

- (void)test
{
    SomeClass *objectA;
    SomeClass *objectB;

    objectA = [[SomeClass alloc]init];
    objectB = objectA;
    NSLog( @"objectA=%p objectB=%p", objectA, objectB );

    objectA = nil;
    NSLog( @"objectA=%p objectB=%p", objectA, objectB );

    NSLog( @"end of test method" );
}

produces this output

objectA=0x7a4d800 objectB=0x7a4d800
objectA=0x0 objectB=0x7a4d800
end of test method
dealloc underlying object
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top