为什么局部变量总是很强?

时间:2014-07-04 17:24:17

标签: objective-c variables block

  1. 根据课堂笔记,据说局部变量总是很强。我真的很想知道它的原因。为什么局部变量总是很强。

  2. BTW,我正在学习积木。据我所知,局部变量应该在方法或块内使用和声明。但是,我在使用块时看到的局部变量在方法外部声明,但在块内部使用。因此,我对此非常好奇。

  3. 局部变量在方法之外的代码如下所示:

    _block BOOL stoppedEarly = NO; // this is the local variable
    double stoppedValue = 52;
    [aDictionary enumerateKeysAndObjectsUsingBlock: ^(id key, id value, BOOL *stop) {
    NSLog (@"value for key %@ is %@", key, value);
    if ([@"ENOUGH" isEqualToString: key] || [value doubleValue] == stoppedValue) {
    *stop = YES;
    stoppedEarly = YES;
    } 
    }];
    

1 个答案:

答案 0 :(得分:0)

1)局部变量强大是有意义的,否则所有对象都会在创建后立即释放,或者您每次都必须添加__strong属性:

UIView *view = [[UIView alloc] init];
//if it wasn't a strong reference, view would be released here
//and you couldn't use the reference in the next line
view.backgroundColor = [UIColor blackColor];

2)您的示例中的Block将为字典中的每个键值对调用一次。由于代码的意图是对所有blockcalls使用一个变量,因此它在它之外声明。想想全局变量和方法。

编辑:这里有一些关于变量范围的基本例子。

//global, visible in all methods
NSInteger globalVariable; 

- (void)someMethod{
    //local, visible only until the end of the method 
    NSInteger localMethodVariable;

    void (^block)() = ^void() {
         //local, visible only until the end of the block
         NSInteger localBlockVariable;

         //may use all 3 variables here
    };

    //may use globalVariable and localMethodVariable here
}

- (void)someOtherMethod{
     //may use globalVariable here
}
相关问题