0
votes

So I'm new to this site, not really sure what the conventions are for how to go about asking a question, but I'm just beginning with Objective-C and have a question relating to the instantiating of objects.

Okay, so I know that the root class NSObject has the class methods alloc and init, and these methods are passed down to any classes that inherit NSObject, which is pretty much every class. I know the typical format for instantiating an object is like this:

MyObject *m = [[MyObject alloc]init];

But considering MyObject has the alloc and init methods inherited from NSObject, this could also theoretically work, considering that MyObject and NSObject have the same alloc and init methods (assuming that the class doesn't override them):

MyObject *m = [[NSObject alloc] init];

And it works for just instantiating, but when I try to call any method in the MyObject class, an NSException is thrown. When I switch the NSObject alloc back to MyObject alloc, it works. I just don't understand why! This is probably a basic question, but any explanation?

Thanks in advance!

Jake

2
What is the exception that is thrown?David Skrundz
@NSArray I'm sure it's an NSInvalidArgumentException - unrecognized selector sent to instance (hex address of instance)user529758

2 Answers

3
votes

The logic is the same, but the class object passed to the implementation of the message alloc is not. In the first case, the compiler transforms your code into:

objc_msgSend([MyObject class], @selector(alloc)];

and thus the implementation of alloc creates an instance of the class MyObject. However, if you write [NSObject alloc]; it is transformed into

objc_msgSend([NSObject class], @selector(alloc)];

So a plain NSObject instance is created, which obviously won't respond to your class' messages.

2
votes
[[NSObject alloc] init]

create a NSObject, no matter if you assign it to an variable of another type, so it does not make much sense to do MyObject *m = [[NSObject alloc] init];, while it can make sense to do something like MyClass *obj = [[MySubClass alloc ] init];, as a MySubClass is also a MyClass.