+ (NSArray *)getArrayOfBubblesWithTitles:(NSArray *)titles andMainBubble:(BubbleContainer *)mainB {
UIColor *c = mainB.colour;
Corner corner = [Styles getCornerForPoint:mainB.frame.origin];
NSMutableArray *blocks = [[NSMutableArray alloc] init];
NSUInteger count = titles.count;
CGSize size = mainB.frame.size;
//TODO: calculation blocks frame
for (int a = 0; a < titles.count; a++) {
PositionCalculationBlock x = ^{
return [SimpleSelectionView getPositionOfObjectAtIndex:a outOfBubbles:count size:size fromCorner:corner];
};
[blocks addObject:x];
}
NSMutableArray *m = [[NSMutableArray alloc] init];
for (int a = 0; a < titles.count; a++) {
[m addObject:[[BubbleContainer alloc] initSubtitleBubbleWithFrameCalculator:blocks[a] colour:c title:titles[a] andDelegate:NO]];
}
return m;
}
我不确定我的 block 在使用变量方面是否能正常工作。在苹果文档中,它说任何更改都会反射(reflect)在封闭的词法范围中,包括在同一封闭的词法范围内定义的任何其他 block 。
我不确定这意味着什么,但我认为这意味着我在哪里在for语句中使用变量a
,每个 block 中只会使用a的最高值,而不是0计数。另外,使用这些实例变量(计数、大小)是否可以避免使用强指针指向像 mainB 这样的对象?这很难测试。我距离运行我的代码还很远,所以如果你对 block 有任何了解,你可以批评一下吗?
谢谢
最佳答案
首先,意识到您引用的那一行:
专门且仅适用于 block 可变变量,即带有__block
修饰符的变量。您向我们展示的代码片段中没有任何 block 可变变量,因此该行不适用。
i think it means that where i use the variable a in the for statement, only the highest value of a will be used in every block instead of 0-count
在 block 中使用但在封闭范围内定义的变量通常是只读的——如果尝试进行更改,编译器会提示该变量不可分配。要进行更改,需要使用 __block
修饰符将变量标记为可 block 修改。对 block 可修改变量所做的更改会反射(reflect)在封闭范围内。
这是一个例子:
{
__block int anInteger = 42;
void (^testBlock)(void) = ^{
NSLog(@"inside the block anInteger is: %i", anInteger);
anInteger = 96;
};
NSLog(@"before the assignment anInteger is: %i", anInteger);
anInteger = 84;
NSLog(@"before the block anInteger is: %i", anInteger);
testBlock();
NSLog(@"after the block anInteger is: %i", anInteger);
}
输出为:
before the assignment anInteger is: 42
before the block anInteger is: 84
inside the block anInteger is: 84
after the block anInteger is: 96
关于variables - Objective C block 和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21561645/