ARC: How to release static variable?

ぐ巨炮叔叔 提交于 2019-12-05 17:28:35

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/7942041/arc-how-to-release-static-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!