Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How safe is it to use Class pointer?

How safe is the use of Class with Objective-C?

-> can i store the Class safe in a dictionary and than compare

info[@"class"] = [User class];
...
if ([User class] == info[@"class"]) {

}

-> can the class pointer change?

-> is it quarantined to be never Nil?

like image 937
Peter Lapisu Avatar asked Nov 19 '14 15:11

Peter Lapisu


1 Answers

Class objects behave like normal objects. They can be retained, released, passed as arguments and return values, stored in ivars and properties, stored in containers — basically, anything.

[SomeClassName class] normally will not compile or link if such class can not be found, but it is possible for it to compile but return nil, for example, when running on OS which does not have that class available, i.e. older OS version than version of your development SDK. The return value of NSClassFromString will be nil, if such class does not exist.

Pointer value (identity) of class objects never changes. There is only one class object for each class name, and you can use C == operator to test if class pointers are the same class. (Subclass/superclass relationship can be tested using + isSubclassOfClass: class method).

Class objects are never deallocated — you can rely on them to be alive (i.e. without retaining them) until the process completely terminates.

The above is true for most applications; however, there is a tricky case of bundle loading (and even more tricky case of bundle unloading):

  • Loading bundle may add classes to the runtime, e.g. causing NSClassFromString to start returning non-nil for their names.
  • If dynamically loading a bundle causes class names to clash, the runtime currently logs a complaint but keeps working; it is not specified what exactly happens in that case.
  • Since Mac OS X 10.5, it is possible to unload a bundle, which causes its classes to be removed. It is not specified what should happen if some of those classes have been retained.
like image 56
hamstergene Avatar answered Oct 21 '22 19:10

hamstergene