How to use __kindof in Objective-C?
Suppose we have this property:
The developer reading this code will have an idea that the array must contain UIView
s, but it is not guaranteed that it will really contain UIView
s, until he reads through all of the code and verifies that indeed only UIView
s were inserted to the array. This case can be resolved using Objective-C’s new features, namely the Generics and __kindof
.
Using Generics, we can declare the property as the following instead.
Anyone who reads this code will understand the array must contain UIView
s. But the catch is, the array must contain only UIView
s, but not instances of subclasses of UIView
s such as UIWebView
s or UIButton
s. Trying to insert a non-UIWebView
objectc will result to a compiler warning. This problem can be resolved using__kindof
.
Using this construct, viewCollection
can contain instances of UIView
s and its subclasses such asUIWebView
s and UIButton
s.
Developers should use the new features of Objective-C if given the chance. The new __kindof
construct will surely help developers improve their code by being specific with their intents. The Generics construct and__kindof
seems strict but I think this is for the good of the developers and the apps that they are making.
=============================================
block对于其变量都会形成strong reference,对于self也会形成strong reference ,而如果self本身对block也是 strong reference 的话,就会形成 strong reference 循环,造成内存泄露,为了防止这种情况发生,在block外部应该创建一个week(__block) reference。
所以在block内如果有self的话,一般都会在block外面加一句_block typeof(self)bself = self;
__block typeof(self) bself = self;
[self methodThatTakesABlock:^ {
[bself doSomething];
}