Why use (__weak class) in a function definition in Objective-C?

I have a factory class that creates a UITableViewCell from the different types that I defined, and called them: TypeATableViewCell and TypeBTableViewCell.

Now the method in my factory class is defined as follows:

+ (UITableViewCell*)getCellForIdentifier:(NSString*)identifier cellClass:(__weak Class)cellClass;

Why did someone decide to use (__weak Class) here instead of just (class).

Thanks Nicolas

+6
source share
1 answer

In general, it does not matter. Class es are interned efficiently - after registering at AFAICT runtime, they can never be unregistered, so the runtime will always “hold” them (so that is). A step through the assembly shows that +[NSObject retain] is no-op (just returns self and does nothing). However, if you create a new root class and try to save it, for example ...

 Class foo = objc_allocateClassPair(nil, "Foo", 0); [foo retain]; 

... runtime will be barf because the new root class does not implement retain , which means that if you want your API to tolerate new root classes that do not implement retain , you should mark them as __weak so ARC does not call retain on them. Therefore, in my opinion, technically, you would always want variables of type Class be weak, but in practice this hardly ever matters, since everything that you would use as a class of a table cell would have to inherit from UITableViewCell anyway (which inherits from NSObject .)

PS: I just went through it, and NSProxy in this respect coincides with NSObject . Only self return appears and do nothing. Therefore, if you do not create new root classes, you will probably safely skip the __weak qualifier.

+10
source

Source: https://habr.com/ru/post/954297/


All Articles