6

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

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

and

class_createInstance(clazz,0);

3 Answers 3

10

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.

2
  • 2
    +1 especially for "unless you ... can answer this question yourself"
    – JeremyP
    Sep 27, 2010 at 16:13
  • Yes, and thanks also to the other comments here, and the macdev irc on freenode, I've started learning about the class clusters, to which I believe you're eluding to... Very interesting stuff...
    – Infrid
    Sep 28, 2010 at 1:27
3

There is a description here:

http://www.cocoabuilder.com/archive/cocoa/111527-class-createinstance-with-nsarray-nsdictionary.html

Basically, class_createInstance is for Cocoa implementors, and gives them low-level access to the process. API users should use alloc, which presumably uses class_createInstance or something like it.

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.