Objective-C Blocks:如果从弱指针调用self,可以在外部方法中修改self吗?

时间:2020-12-21 22:52:09

Can you modify self from an instance method called from a weak self pointer within a block?

你能从一个块中弱自指针调用的实例方法修改self吗?

-(void)someMethod:(AnotherClassName *)anObject {

    __weak MyClassName *weakSelf = self;

    [anObject requestSomethingWithCompletion:^{
        [weakSelf updateSomething];
    }];
}

-(void)updateSomething {
    self.something = @"update"; // Will this cause a memory leak?
}

So basically I am calling an instance method from the same class I am in, but I am doing it from a weak pointer and then changing self.

所以基本上我从我所在的同一个类中调用一个实例方法,但是我是从弱指针进行调用然后改变自我。

According to Apple's Programming with Objective-C Guide this is how to call a method on self within a block but it isn't clear weather I can directly modify self in that method.

根据Apple的Objective-C编程指南,这是如何在一个块中调用自我的方法,但不清楚天气我可以直接修改该方法中的自我。

If you know the answer based on something you've read before please include the source.

如果您根据之前阅读过的内容了解答案,请提供来源。

Thanks!

谢谢!

1 个解决方案

#1


4  

You can modify properties and call methods. There will be no memory leaks.

您可以修改属性和调用方法。不会有内存泄漏。

But your block is not thread safe now. If requestSomethingWithCompletion will run block asynchronously your class (self) could be deallocated during block execution and weakSelf will become nil. This could cause problems (depends on what does your block do). Good practice to avoid this is to write it following way

但是你的块现在不是线程安全的。如果requestSomethingWithCompletion将异步运行块,则在块执行期间可以释放类(self),而weakSelf将变为nil。这可能会导致问题(取决于您的块做什么)。避免这种情况的良好做法是按照以下方式编写

-(void)someMethod:(AnotherClassName *)anObject {

    __weak MyClassName *weakSelf = self;

    [anObject requestSomethingWithCompletion:^{
        MyClassName *strongSelf = weakSelf;
        [strongSelf updateSomething];
    }
}

-(void)updateSomething {
    self.something = @"update"; // No leaks here!
}

#1


4  

You can modify properties and call methods. There will be no memory leaks.

您可以修改属性和调用方法。不会有内存泄漏。

But your block is not thread safe now. If requestSomethingWithCompletion will run block asynchronously your class (self) could be deallocated during block execution and weakSelf will become nil. This could cause problems (depends on what does your block do). Good practice to avoid this is to write it following way

但是你的块现在不是线程安全的。如果requestSomethingWithCompletion将异步运行块,则在块执行期间可以释放类(self),而weakSelf将变为nil。这可能会导致问题(取决于您的块做什么)。避免这种情况的良好做法是按照以下方式编写

-(void)someMethod:(AnotherClassName *)anObject {

    __weak MyClassName *weakSelf = self;

    [anObject requestSomethingWithCompletion:^{
        MyClassName *strongSelf = weakSelf;
        [strongSelf updateSomething];
    }
}

-(void)updateSomething {
    self.something = @"update"; // No leaks here!
}