Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between doing alloc and class_createInstance

Tags:

objective-c

Wondering, what is the difference between creating a class with:

Class clazz = [NSString class];
[clazz alloc];

and

class_createInstance(clazz,0);
like image 379
Infrid Avatar asked Sep 27 '10 15:09

Infrid


2 Answers

Basically, you shouldn't be using class_createInstance() unless you know enough about what you're doing that you can answer this question yourself.

Calling class_createInstance() bypasses any special cases that have been implemented in +alloc. If you try it with NSString, you will get an NSString instance, not an instance of the private placeholder class that is the proper target for whatever -init... message you want to send it.

like image 66
NSResponder Avatar answered Nov 15 '22 06:11

NSResponder


One is a function, the other is a method. The function, by virtue of being a function, cannot be overloaded. The method, (since it's a method) could conceivably be implemented in a different manner.

For example, since some classes in Cocoa (collections, for example) are class clusters, it's possible that they override +alloc to implement custom behavior. You could not do that with when using a function.

like image 32
Dave DeLong Avatar answered Nov 15 '22 07:11

Dave DeLong