【问题标题】:Should I set __block variable to nil here and why?我应该在这里将 __block 变量设置为 nil 吗?为什么?
【发布时间】:2012-06-12 15:47:00
【问题描述】:

这是Why do we have to set __block variable to nil?的延续

基本上使用块会导致 ARC 中的保留循环,我仍然不太明白为什么

http://developer.apple.com/library/mac/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW11

-(void)getReviewAndView{
    if(![[GrabClass grab] cekInet]){return;}
    CM(@"get review and view");
    self.viewlbl.text=@"0 view";
    self.reviewlbl.text=@"0 review";

    Business * businessReviewed = [BNUtilitiesQuick currentBusiness];

    NSString *alamat=[NSString stringWithFormat:@"http://...",businessReviewed.ID];

    CLog(@"alamat:%@", alamat);

    __block NSDictionary * dic = nil;


    [Tools doBackground:^{
        dic=(NSDictionary *)[GrabClass JsonParser:alamat]; //dic get set here
        [Tools doForeGround:^{
            NSString *countView= [[dic objectForKey:businessReviewed.ID] objectForKey:@"CountViews"];

            CLog(@"countView:%@", countView);
            NSString *countReview=[[dic objectForKey:businessReviewed.ID] objectForKey:@"Review"]; //dic get used here
            NSString * reviews=@"review";
            NSString * view=@"view";


            //blablabla

            self.viewlbl.text=[NSString stringWithFormat:@"%@ %@",countView,view ];
            self.reviewlbl.text=[NSString stringWithFormat:@"%@ %@",countReview,reviews];
            dic =nil; //should this be called? What happen if it doesn't?
        }];
    }];
}

【问题讨论】:

    标签: objective-c automatic-ref-counting


    【解决方案1】:

    如果您不知道是否有保留周期,您应该在 Instruments 中的“泄漏”工具下运行您的代码,它会告诉您任何泄漏或保留周期。

    另请注意,在最新版本的 Xcode 中,如果您创建这些父/块循环之一,编译器将为您生成警告。

    在你的情况下,你可能不需要担心。 dic 不保留引用它的块,所以这里没有循环。但最好的检查方法是使用泄漏/分配工具。

    【讨论】:

    • 啊,我明白了。因此,如果对象不包含对块的引用,那么就没有真正的问题。谢谢。
    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    相关资源
    最近更新 更多