I use the following code to alloc and init a class in objective c. The class is a cocoa touch class. I try to initialize the class with the code below.
MyClass *myClass;
myClass=[MyClass alloc];
myClass=[MyClass init];
It crashes at
myClass=[MyClass init];
saying
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** [MyClass<0x100b075d0> init]: cannot init a class object.'
If i use
myClass=[[MyClass alloc] init];
It works. Any idea why this happens?
CodePudding user response:
[MyClass alloc]
calls the alloc
method on the class MyClass
. It returns an instance of MyClass
, ready to be initialised, which you do by calling init
on the returned instance.
Classically you write [[MyClass alloc] init]
in Objective-C because there's nothing you can or should be doing between allocating and initialising.
In your code, [MyClass init]
is treating init like a class method, which it is not.
MyClass *myClass;
myClass = [MyClass alloc];
myClass = [myClass init];
Would probably work (note I'm calling init
on myClass
, not MyClass
, but it would upset any future readers and make them wonder why you're not just doing it the normal way.