10

Will dealloc (below) release the NSString pointed to by the static variable exampleString?

// ExampleClass.h

@interface ExampleClass : NSObject

@end

// ExampleClass.m

static NSString *exampleString;

@implementation ExampleClass

- (void)dealloc {
    exampleString = nil;
}

- (id)init {
    self = [super init];
    if (self) {
        exampleString = [NSString stringWithFormat:@"example %@", @"format"];
    }
    return self;
}

@end
Philipp Schlösser
  • 5,179
  • 2
  • 38
  • 52
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • 3
    This is an odd example. Firstly, `static` as used in your code doesn’t mean storage duration but visibility (linkage) instead. Secondly, it looks like you either want class methods as opposed to instance methods, or `exampleString` should be an instance variable. What exactly are you trying to accomplish? –  Oct 30 '11 at 22:17
  • @Bavarious, you're right. This is an odd example. If you point me to a better example. I'm not actually doing this. Feel free to edit it. – ma11hew28 Oct 31 '11 at 15:04
  • 1
    I’m not sure, @Matt. If the code is modified to use class methods then there’s no need for `-dealloc`. If the code is modified to use an instance variable then ARC takes care of releasing it. Moreover, `static` doesn’t really influence the code since its function there is to limit the visibility/linkage of that variable to ExampleClass.m — memory management would be the same if `static` were removed. –  Nov 01 '11 at 04:04

1 Answers1

20

Yes, because since you did not specify an ownership qualifier, the LLVM compiler infers that exampleString has __strong ownership qualification.

This means that by setting exampleString to nil in dealloc, you are retaining nil (the new value), which does nothing, and releasing the old value.

Source

According to section 4.4.3. Template arguments of the LLVM documentation on Objective-C Automatic Reference Counting (ARC), "If a template argument for a template type parameter is an retainable object owner type that does not have an explicit ownership qualifier, it is adjusted to have __strong qualification."

And, according to section 4.2. Semantics, "For __strong objects, the new pointee is first retained; second, the lvalue is loaded with primitive semantics; third, the new pointee is stored into the lvalue with primitive semantics; and finally, the old pointee is released. This is not performed atomically; external synchronization must be used to make this safe in the face of concurrent loads and stores.

ma11hew28
  • 121,420
  • 116
  • 450
  • 651