2

为什么这样有效:

- (void) setupInteraction:(IBITSInteraction*)interaction withInfo:(NSDictionary*)info
{    
    CGRect rect = ([info objectForKey:kInteractionFrameKey] ? CGRectFromString([info objectForKey:kInteractionFrameKey]) : CGRectZero);
    interaction.frame = rect;
    ...
}

为什么这不呢?:

- (void) setupInteraction:(IBITSInteraction*)interaction withInfo:(NSDictionary*)info
{    
    interaction.frame = ([info objectForKey:kInteractionFrameKey] ? CGRectFromString([info objectForKey:kInteractionFrameKey]) : CGRectZero);
    ...
}

我觉得完全一样。。。

  • 编译器:LLVM GCC 4.2
  • 错误(第二种情况):只读变量“prop.283”的赋值
  • 属性框架:@property (nonatomic, assign) CGRect frame;与其各自的@synthesize

提前致谢。

4

2 回答 2

3

这是 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。

于 2011-09-17T01:35:00.100 回答
0

我在 GCC 4.2、LLVM GCC 4.2 和 Apple LLVM 2.1 下的通用通知方法上尝试了此代码。他们都没有给我错误。因此,您的 Xcode 安装和/或编译器安装出现了问题。

于 2011-09-16T23:13:14.877 回答