In Objective-C, why can’t we use
@interface Animal : NSObject {
int state = AnimalStateAlive; // a constant which is 1 to indicate alive
int x = 0;
int y = 0;
}
@properties int energyLevel = 100;
and the compiler can fill in those values right after the alloc has happened?
Because there’s no such thing as a constructor in objective-C.
+allocis a method implemented by NSObject specifically, and the compiler has no idea when/how it is called. To provide initialization, the runtime (class_createInstance(), to be precise) zeroes out the whole instance upon creation, and in fact, this is what is implemented in+alloc.