在下面的代码中,当我在 GCC_OPTIMIZATION_LEVEL 设置为 None 的情况下运行它时,执行工作如我所料,并将以下内容打印到控制台:
My Obj - SomeObj
但是,当我在 Xcode 目标配置中将 GCC_OPTIMIZATION_LEVEL 设置为 Fastest, Smallest 时(通常用于发布版本),我最终会在控制台上打印以下内容:
My obj - (null)
当我将对象存储到 [Foo doSomething] 中的 __weak id myObj 变量中时,该对象似乎正在被释放。如果我从 myObj 变量中删除 __weak 标志,则当 GCC_OPTIMIZATION_LEVEL 设置为 Fastest, Smallest 时,代码将按预期运行。
我基于我在另一个项目中的类似模式构建了这个示例,并添加了 __weak 标志,因为我遇到了保留周期。保留周期警告消失了,但是当我为 Release 构建时,我发现 myObj 在到达我在此示例中记录它的位置时将为零。
设置 __weak 标志违反了哪些规则?
#import "FFAppDelegate.h"
///////////////////////////////////////////////////////
@interface SomeObject : NSObject
@end
@implementation SomeObject
- (NSString *)description; {
return @"SomeObject";
}
@end
///////////////////////////////////////////////////////
@interface Factory : NSObject
@end
@implementation Factory
- (id)generateObj {
id myObj = nil;
if (!myObj) {
SomeObject *anObj = [[SomeObject alloc] init];
myObj = anObj;
}
return myObj;
}
@end
///////////////////////////////////////////////////////
@interface Bar : NSObject
- (id)barObj;
@end
@implementation Bar
{
Factory *factory;
}
- (id)init {
self = [super init];
if (self) {
factory = [[Factory alloc] init];
}
return self;
}
- (id)barObj {
id anObj = [factory generateObj];
return anObj;
}
@end
///////////////////////////////////////////////////////
@interface Foo : NSObject
@property (strong) Bar *aBar;
- (void)doSomething;
@end
@implementation Foo
- (id)init {
self = [super init];
if (self) {
_aBar = [[Bar alloc] init];
}
return self;
}
- (void)doSomething {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
__weak id myObj = [self.aBar barObj];
NSLog(@"My Obj - %@", myObj);
});
}
@end
///////////////////////////////////////////////////////
@implementation FFAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
Foo *f = [[Foo alloc] init];
[f doSomething];
}
@end