Weak Self in Blocks

前端 未结 3 819
[愿得一人]
[愿得一人] 2021-01-06 23:55

Do I need to check if weak self is nil in blocks?

I create weakSelf pointer like:

__weak typeof(self) weakSelf = self;

and in the b

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-07 00:52

    It seems quite unnecessary since calling a message on nil is a no-op. (Nothing happens)

    ^{
        [weakSelf doSomething]; //Does nothing if weakSelf is nil
    }
    

    The only reason I can think you might want to do this is if other messages (not on self) shouldn't be called

    ^{
        // Here I don't want to add weakSelf as an observer if it's nil
        if (!weakSelf) return;
    
        [OtherClass addObserverForSomething:weakSelf];
    }
    

提交回复
热议问题