I write some code use objective-c block, but the result confused me.
@interface MyTest : NSObject
@end
@implementation MyTest
- (void)test {
NSArray *
I tried a fourth case that also works just fine:
- (NSArray *)array4 {
int a = 10;
return @[ ^{
NSLog(@"block0: a is %d", a);
}, ^{
NSLog(@"block1: a is %d", a);
}
];
}
Of course this is the same as:
- (NSArray *)array4 {
int a = 10;
id blocks[] = { ^{
NSLog(@"block0: a is %d", a);
}, ^{
NSLog(@"block1: a is %d", a);
}
};
NSUInteger count = sizeof(blocks) / sizeof(id);
return [NSArray arrayWithObjects:blocks count:count];
}
So the only issue is with "array2". The key point with that implementation is that you are calling the arrayWithObject:
method which takes a variable number of arguments.
It seems that only the first (named) argument is properly copied. None of the variable arguments are copied. If you add a third block the problem still arises on the 2nd block. Only the first block is copied.
So it seems that using the blocks with the variable argument constructor, only the first named argument is actually copied. None of the variable arguments are copied.
In all other approaches to creating the array, each block is copied.
BTW - I ran your code and my additions using Xcode 4.6.2 using a simple OS X app under Lion (10.7.5) using ARC. I get identical results when the same code is used in an iOS 6.1 app.