iOS 关于Block的使用及循环引用

来源:互联网 发布:mac pro风扇声音很大 编辑:程序博客网 时间:2024/05/16 11:14


     BlockButton *button = [[BlockButton alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];    [button setTitle:@"touch me" forState:UIControlStateNormal];    button.backgroundColor = [UIColor orangeColor];    [self.view addSubview:button];    [button release];    //    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"jack", nil]; //1//    NSLog(@"1.block访问前 array.retainCount=%d",array.retainCount);//    //创建block块,传个button,当button被按下时则调用此block//    /*//     当此block被copy后,如果block访问了局部对象//     则会将block中引用的局部对象都retain一下,防止此对象被销毁掉//     *///    [button addTouchBlock:^(BlockButton *button) {//        NSLog(@"array=%@",array);//        NSLog(@"2.block访问后 array.retainCount=%d",array.retainCount);//    }];    //    [array release];    /*     当此block被copy后,如果block访问了当前对象的实例变量或方法,则会对当前对象retain     */    __block DetialViewController *this = self;    NSLog(@"1.block访问前,self.retainCount=%d",self.retainCount);    [button addTouchBlock:^(BlockButton *button) {        NSLog(@"%@",this->_data);        NSLog(@"2.block访问后%d",this.retainCount);    }];    //    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];        //    [UIView beginAnimations:nil context:nil];//    [UIView setAnimationDuration:0.4];//    ////    button.frame = CGRectMake//    [UIView commitAnimations];            [UIView animateWithDuration:0.4 animations:^{//        button.frame = CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>);    }];        }//- (void)buttonAction {//    NSLog(@"2.block访问后,%d",self.retainCount);//}


1 0