【问题标题】:weakSelf on queue calling method that use self inside使用 self 的队列调用方法上的 weakSelf
【发布时间】:2014-03-20 15:56:12
【问题描述】:

如果我这样做可以吗:

  -(void)example{
       __weak __typeof__(self) weakSelf = self;

       dispatch_queue_t dispatchQueue = dispatch_queue_create("q_getRestaurants", NULL);
       dispatch_async(dispatchQueue, ^{

           dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf doSomething];
           });
       });
    }



   -(void)doSomething{
       //can i use self inside this method????
       self.view.backgroundColor = [UIColor redColor];
   }

问题是我想知道如果我在 do something 方法中使用 self 是否可以,该方法是从具有弱自我调用的队列中调用的。

【问题讨论】:

  • 你是说在“//Call something from server”部分你想引用self
  • 不,问题是我是否可以调用 [weakSelf doSomething] 并在 doSomething 方法中使用 self
  • 是的,你可以。在一个方法(除了 init 之外)中,您可以保证 self 始终是一个有效值。如果 self 已被释放,并且 weakSelf 自动设置为 nil,那么 [weakSelf doSomething]; 将不做任何事情并且不会实际调用 doSomething。
  • 这个问题对你来说可能很有趣stackoverflow.com/questions/22339490/arc-self-and-blocks
  • @David:你可以保证self(像所有参数一样)在方法的开头指向一个有效值。不晚。

标签: ios objective-c automatic-ref-counting objective-c-blocks


【解决方案1】:

是的。你在那里很好。仅保留块本身内的变量。

【讨论】:

  • 那么,如果我在 doSomething 方法中使用 self 如果我从 weakSelf 指针调用它,那么不管它吗?
  • 正确。尽管您可能想考虑在块内创建一个 strongSelf 以确保 weakSelf 不会被取消。这取决于自我是什么。如果它是一个 appDelegate 或其他你不需要担心的东西,因为它不会去任何地方。
猜你喜欢
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 2011-09-28
  • 2023-03-07
  • 2013-09-11
相关资源
最近更新 更多