Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a factory class that builds UITableViewCell of different types that I have defined, let's call they: TypeATableViewCell and TypeBTableViewCell.

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

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

Why would someone choose to use (__weak Class) here instead of just (Class).

Thanks, Nicolas

like image 295
Nicolas M. Avatar asked Sep 20 '13 21:09

Nicolas M.


1 Answers

In general, this won't matter. Classes are effectively interned -- once registered with the runtime, AFAICT, they can never be unregistered, so the runtime will always be "retaining" them (such that it is). Stepping through the assembly shows that +[NSObject retain] is a no-op (just returns self, and does nothing else). However, if you create a new root class and try to retain it, like this...

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

... the runtime will barf, because the new root class doesn't implement retain meaning that if you wanted your API to tolerate new root classes that don't implement retain you would have to mark their uses as __weak so that ARC didn't call retain on them. So I guess, technically you would always want variables of type Class to be weak, but in practice it's unlikely to ever matter, since anything you would be using as a table cell class would have to inherit from UITableViewCell anyway (which inherits from NSObject.)

PS: Just stepped through it and NSProxy is the same as NSObject in this regard. Appears to just return self and do nothing else. So unless you're off creating new root classes, you're probably safe skipping the __weak qualifier.

like image 128
ipmcc Avatar answered Nov 04 '22 01:11

ipmcc