iphone - 奇怪的赋值错误

标签 iphone objective-c ipad llvm-gcc

为什么这有效:

- (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(非原子,分配)CGRect 框架; 及其各自的 @synthesize

提前致谢。

最佳答案

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

关于iphone - 奇怪的赋值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7451162/

相关文章:

iphone - 如何检查哪个选项卡栏项目处于事件状态?

iphone - NSHTTPCookieStorage 的共享实例不会保留 cookie

ios - Objective-C HealthKit 识别源是来自 Apple iPhone 还是 Apple Watch

iphone - 如何以编程方式加载 UIViewController

iphone - OpenGL ES - glDrawElements - 难以理解索引

ios - iPad画中画随机调用restoreUserInterfaceForPictureInPictureStopWithCompletionHandler

ios - 是否可以在 Apple 设备(即 Iphone、Ipad)上跟踪 cookie 等

ios - 如何针对 NSUserDefaults 使用 Touch ID?

java - 如何在 iOS 上的 Turbo 模块中发出事件

ios - Objective-C:淡化 GUI