iOS >> block >> 更改 block 外部变量的值

标签 ios objective-c block variable-assignment objective-c-blocks

我熟悉 __block 语句,它使变量在 block 中“可分配”。 但是我看到,当使用一些使用 block 作为方法中的参数的 Objective-C 功能时,一些变量是可分配的,即使它们没有用这个 __block 语句声明。

这里有2个代码例如:

[UIView animateWithDuration:2 animations:^
     {
         self.animatedView.backgroundColor = [UIColor blueColor];
         self.animatedView.center = CGPointMake(100, 100);
     }];

(animatedView 是一个与 IBOutlet 连接的简单 UIView)。

    int myInt = 10;
    NSMutableString* mString = [NSMutableString stringWithString:@"Mutable Hello"];
    NSString* imString = @"Imutable Hello";

    void (^myBlock)(void) = ^
    {
        [mString appendString:@" Block"]; //working
        imString = @"Imutable Hello Block"; //error
        myInt = 11; //error
    };

我的问题是:我怎么能为 UIView 实例属性赋值?

我不是在寻址对象并更改它,就像我的 mString。

我希望“center”属性的行为类似于我的 myInt,因为它是一个直接访问的 C 结构,而不是指向对象的指针。

我希望“backgroundColor”表现得像我的 imString,因为它是一个指向分配有新对象的对象的指针,不是吗?

我无法在文档中找到令人满意的解释...如果有人能提供一个,或向我介绍一个,我将不胜感激。

最佳答案

这就是assignment和usage的区别。用法是方法调用。您完全可以在实例上调用方法 ([mString appendString:@"Block"];//working) 但您不能分配 (imString = @"Imutable Hello Block";//error) 没有标记变量来告诉编译器它应该启用它。

这段代码:

self.animatedView.backgroundColor = [UIColor blueColor];

仍然不是真正的赋值,它是一个“隐藏”的方法调用。点符号从来都不是赋值,它是方法调用的语法糖。它实际上转化为:

[[self animatedView] setBackgroundColor:[UIColor blueColor]];

分配给局部变量和分配给对象内部变量的区别在于它们在内存中驻留的位置。基本上,它们会存在足够长的时间以发挥作用。这是栈上和堆上数据的区别。

关于iOS >> block >> 更改 block 外部变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21675131/

相关文章:

ios - Swift 2 无法删除可选绑定(bind)

ios - 如何捕获 "incoming call"而不是引导到后台?

iphone - 如何使用 Storyboard呈现启动/登录 View Controller

iphone - 将 NSTimeInterval 持续时间转换为 NSString

javascript - 选择更改时阻止多个选择滚动到顶部

authentication - 使用 swift 验证 GameKit 本地播放器

ios - 用于 2 个 TableViews/Segmented Control Swift 的自定义单元格

ios - touchesBegan 和 touchesEnded 在 Xcode 6.3 更新后返回不同的触摸位置

objective-c - FM数据库 : is it safe to leave failing inserts (unique PK key violated)?

sockets - 如何知道继续从套接字输入流读取是否安全(避免读取 block )