FreeNickname
FreeNickname

Reputation: 7764

Why isn't the `assign` property deallocated under ARC? Pure luck?

UPDATE: I thought the default behavior under ARC is assign, but it is strong. So, don't bother reading the question, it is useless :)


Consider the following code:

#import "AppDelegate.h"

@interface TestClass: NSObject
@property (atomic) NSMutableArray *strings; //"assign" by default
@end
@implementation TestClass
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    TestClass *testObject = [TestClass new];
    testObject.strings = [[NSMutableArray alloc] init];
    //(*) Why isn't strings array deallocated here under ARC? There are no strong references to it.
    [testObject.strings addObject:@"str1"];
    [testObject.strings addObject:@"str2"];
    [testObject.strings addObject:@"str3"];
    NSLog(@"Strings: %@", testObject.strings);
    return YES;
}
@end

Here strings property is declared as assign (by default). So, if I'm not mistaken, there are no strong references to this array in the code at all. So, from my point of view strings should be deallocated at (*). However, the code works and prints the array.

Why? My possible explanation is that there are some implementation details related to the NSMutableArray, so there are some internal references left to the strings array, so it remains valid. So it is just pure luck. Am I right? I've tricked the system into returning retainCount, it was equal to 2 at the point of NSLog.

If I change the property declaration to (atomic, weak), the array is nil as expected.

I use Xcode 7.1.1 (7B1005) with OS X 10.11.2 (15C30). I checked the DEBUG version in the iOS simulator.

I found a code like this on the internet, and expected it to crash, but it didn't. Hence the question.

Upvotes: 0

Views: 24

Answers (1)

CRD
CRD

Reputation: 53000

Under ARC the default ownership is strong not assign, see the Clang ARC documentation for details.

Upvotes: 1

Related Questions