Reputation: 80
File Person.h
@interface Person:NSObject
+ (void)callBlock:(void (^)())block;
@end
File Person.m
@imp:
+ (void)callBlock:(void (^)())block
{
[NSThread sleepForTimeInterval:2];
block();
}
@end
Code in ViewDidLoad:
Person *p = [[Person alloc] init];
void (^block)() = ^{
NSLog(@"%@",p);
[p release];
}
[Person callBlock:block];
finish!
MyQuestion:
in main function, block var is a stackblock,and this block assign to the function +callBlock:,and the block in Person.m is also a stackblock. Content of them are same.
In my opinion,the block in main will be free by system before called in Person.m, so I think this program will crash, but it run normal. why?
And i think my code is same as below.
...
void example_addBlockToArray(NSMutableArray *array) {
char b = 'B';
[array addObject:^{
printf("%cn", b);
}];
}
void example() {
NSMutableArray *array = [NSMutableArray array];
example_addBlockToArray(array);
void (^block)() = [array objectAtIndex:0];
block();
}
This programe crashed! which the difference between them?
Sorry! both program use mrc!!! i did not write clearly!
Upvotes: 1
Views: 177
Reputation: 116
As it seems, you're using manual memory management.
Therefore is an explanation:
Person object case
Char log case
Since you're not using ARC, it goes this way:
So, that's it.
Upvotes: 2
Reputation: 7552
As pointed out in the comments, the first example does not crash because the block is defined in a function scope which doesn't end until after the block is called.
The second example, on the other hand, defines the block in a secondary function, which ends before the block is called. Thus, at the time of the block invocation, the stack has already been modified and the block has become invalid.
Upvotes: 1
Reputation: 241
After main function executed the block in main will be free by system ,not before called in Person.m. I tried the second code in viewcontroller, it works fine, not crash.
Upvotes: 0