ios block(3)
来源:未知 责任编辑:责任编辑 发表时间:2015-09-17 09:44 点击:次
p>IntToStringConverter independentBlockObject = ^(id self, NSInteger paramInteger) {
p> KSLog(@" >> self %@, memberVariable %d", self, [self memberVariable]);
p>
p> NSString *result = [NSString stringWithFormat:@"%d", paramInteger];
p> KSLog(@" >> independentBlockObject %@", result);
p> return result;
p>};
p>
p>
p>- (void)testAccessSelf
p>{
p> // Independent
p> //
p> [self convertIntToString:20 usingBlockObject:independentBlockObject];
p>
p> // Inline
p> //
p> IntToStringInlineConverter inlineBlockObject = ^(NSInteger paramInteger) {
p> KSLog(@" >> self %@, memberVariable %d", self, self.memberVariable);
p>
p> NSString *result = [NSString stringWithFormat:@"%d", paramInteger];
p> KSLog(@" >> inlineBlockObject %@", result);
p> return result;
p> };
p> [self convertIntToStringInline:20 usingBlockObject:inlineBlockObject];
p>}
p>
p>
p>
p>
p>
p>
p>3,使用 weak–strong dance 技术来避免循环引用
p>
p>
p>在第二条中,我提到内联 block 可以直接引用 self,但是要非常小心地在 block 中引用 self。因为在一些内联 block 引用 self,可能会导致循环引用。如下例所示:
p>
p>
p>[cpp]
p>@interface KSViewController ()
p>{
p> id _observer;
p>}
p>
p>
p>@end
p>
p>
p>@implementation KSViewController
p>
p>
p>- (void)viewDidLoad
p>{
p> [super viewDidLoad];
p> // Do any additional setup after loading the view, typically from a nib.
p>
p> KSTester * tester = [[KSTester alloc] init];
p> [tester run];
p>
p> _observer = [[NSNotificationCenter defaultCenter]
p> addObserverForName:@"TestNotificationKey"
p> object:nil queue:nil usingBlock:^(NSNotification *n) {
p> NSLog(@"%@", self);
p> }];
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>