Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 我可以对弱参数的赋值强制发出警告吗?_Objective C_Compiler Warnings_Weak References_Autorelease - Fatal编程技术网

Objective c 我可以对弱参数的赋值强制发出警告吗?

Objective c 我可以对弱参数的赋值强制发出警告吗?,objective-c,compiler-warnings,weak-references,autorelease,Objective C,Compiler Warnings,Weak References,Autorelease,我看到了中描述的情况,但有一个重要的警告。考虑这个代码: @implementation UIAlertView (Factory) + (instancetype)alertViewWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelBut

我看到了中描述的情况,但有一个重要的警告。考虑这个代码:

@implementation UIAlertView (Factory)

+ (instancetype)alertViewWithTitle:(NSString *)title
                           message:(NSString *)message
                          delegate:(id)delegate
                 cancelButtonTitle:(NSString *)cancelButtonTitle
                 otherButtonTitles:(NSArray *)otherButtonTitles
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];
    for (NSString *otherButtonTitle in otherButtonTitles)
    {
        [alertView addButtonWithTitle:otherButtonTitle];
    }
    return alertView;
}

@end
如果我这样做:

@property (nonatomic, weak) UIAlertView *alertView;

...

self.alertView = [UIAlertView alertViewWithTitle:@"Hi" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[self.alertView show];
当我在调试模式下构建时,它会工作——即factory方法返回一个自动释放指针,因此
self.alertView
有一个值。显示后,它将保留在视图层次结构中。不过,这不是我想做的事情——这是一个错误,在我为发行版构建时,它作为一个实际问题出现了:编译器(逻辑上)似乎优化了赋值,使
self.alertView
等于
nil

即使我将分析器切换到在我的发布版本上运行,它也不会标记弱指针的使用


有没有办法让编译器/预编译器标记此项?

添加此项以获得您期望的行为

@autoreleasepool {
    self.alertView = [UIAlertView alertViewWithTitle:@"my alert view"];
}
[self.alertView show];
使用ARC不能保证您的对象会立即清理。编译器不知道工厂方法是否正在添加强引用。可能是

这将涉及更多细节


静态方法并不总是与alloc init相同。编译器无法区分+(id)makeMyObject和+(id)GetMyObject之间的区别,因为它们已经存在,并且由SomeBodyElse管理。

您应该看到此警告
将保留对象分配给弱属性;对象将在分配后释放
。只是设法重现您的问题,非常奇怪。我希望它能被清理干净。作为一个工厂方法的某些东西正在改变这一点。@CrimsonChris的可能副本我同意这是一个相关的问题,但没有说明当我编写这样做的代码时如何得到警告。编译器没有通过故意选择提前释放对象来进行优化。相反,发布版本中的优化启用了
objc\u autoreleaserentvalue()
magic,避免将对象放入自动释放池。因此,ARC总是在代码中发布释放对象。自动释放池中不再有未完成的引用。当+1引用被分配给弱属性,而您的属性是+0引用时,编译器会发出警告。如果它要对此发出警告,它必须警告所有对弱属性的赋值。即使我这样做,我也看不到警告。只有将其分配给“[[UIAlertView alloc]init]”时,我才会收到警告。您不会收到警告,因为
alertViewWithTitle
可能会在幕后创建强引用。编译器不会分析我的自定义工厂方法。因此,您的回答是“添加此项以获得您期望的行为”,但我期望的行为是一个警告,但这并不能实现。此外,将每个作业包装在自动释放池中并不是一个合理的解决方案。我同意您不应该在这里使用自动释放池,这个答案试图解释为什么您无法获得预期的警告。