这是 GCC 4.2 前端的一个错误,也可以在 LLVM-GCC 4.2 中重现。恭喜!当分配的值是由条件运算符产生的表达式时,这些编译器在使用点语法进行属性分配时会出现问题。
以下代码重现了该问题并显示了两种源代码解决方案:如您所见,一种是使用临时变量。另一种解决方案是使用传统的 Objective-C 消息发送语法而不是点语法:
#import <Foundation/Foundation.h>
CGRect CGRectFromString(NSString *string);
@interface SomeClass : NSObject
@property (nonatomic, assign) CGRect frame;
@end
@implementation SomeClass
@synthesize frame;
@end
int main(void) {
NSDictionary *info;
SomeClass *interaction;
NSString *kInteractionFrameKey;
CGRect rect;
rect = [info objectForKey:kInteractionFrameKey] ? CGRectFromString([info objectForKey:kInteractionFrameKey]) : CGRectZero;
interaction.frame = rect;
[interaction setFrame:([info objectForKey:kInteractionFrameKey] ? CGRectFromString([info objectForKey:kInteractionFrameKey]) : CGRectZero)];
interaction.frame = ([info objectForKey:kInteractionFrameKey] ? CGRectFromString([info objectForKey:kInteractionFrameKey]) : CGRectZero);
interaction.frame = ([info objectForKey:kInteractionFrameKey] ? CGRectZero : CGRectFromString([info objectForKey:kInteractionFrameKey]));
interaction.frame = ([info objectForKey:kInteractionFrameKey] ? CGRectZero : CGRectZero);
return 0;
}
使用不同的编译器进行测试会产生以下结果:
$ llvm-gcc -c test.m
test.m: In function ‘main’:
test.m:24: error: assignment of read-only variable ‘prop.76’
test.m:25: error: assignment of read-only variable ‘prop.77’
test.m:26: error: assignment of read-only variable ‘prop.78’
$ clang -c test.m
$
在这种特殊情况下,您可以使用 LLVM 或避免使用点语法。你可能想提交一个错误,但我不会屏住呼吸,因为 Apple 不太可能更新 GCC。