你可以从一个块中弱自指针调用的实例方法修改self吗?
-(void)someMethod:(AnotherClassName *)anObject {
__weak MyClassName *weakSelf = self;
[anObject requestSomethingWithCompletion:^{
[weakSelf updateSomething];
}];
}
-(void)updateSomething {
self.something = @"update"; // Will this cause a memory leak?
}
所以基本上我从我所在的同一个类调用一个实例方法,但是我是从一个弱指针开始,然后改变self
。
根据Apple's Programming with Objective-C Guide,这是如何在一个区块内调用self
上的方法,但天气不明确我可以直接修改该方法中的self
。
如果您根据之前阅读的内容了解答案,请加入来源。
谢谢!
答案 0 :(得分:4)
您可以修改属性和调用方法。没有内存泄漏。
但是你的块现在不是线程安全的。如果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!
}