Jeremy L
Jeremy L

Reputation: 3810

In Objective-C, why can't an object's instance variables or properties have default values?

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?

Upvotes: 2

Views: 124

Answers (4)

justin
justin

Reputation: 104698

The common case (strictly objc) has been answered.

As an alternative solution, you can accomplish exactly this using C++ types for your instance variables. With a C++ instance variable, C++ types will be initialized using their default constructors.

For example:

namespace MON {
    class t_animal {
    public:
        t_animal() :
          state(AnimalStateAlive),
          x(0),
          y(0),
          energyLevel(100) {
        }
        /* ... */
    private:
        int state;
        int x;
        int y;
        int energyLevel;
    };
} /* << MON */

@interface Animal : NSObject
{
@private
    MON::t_animal animal;
}

@end

Upvotes: 0

user529758
user529758

Reputation:

Because there's no such thing as a constructor in objective-C. +alloc is 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.

Upvotes: 3

Hailei
Hailei

Reputation: 42163

Refer to The Objective-C Programming Language:

The alloc method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all, that is, except the isa variable that connects the new instance to its class. For an object to be useful, it generally needs to be more completely initialized. That’s the function of an init method.

Upvotes: 1

You should use the designated initializer for that matter, just implement init method. The reason why is just the language doesn't provide a special syntax for class initialization.

Upvotes: 0

Related Questions