Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are instance variables defined in the header file in Objective-C

Tags:

objective-c

I can understand defining the functions in the @interface of the header file, but why the instance variables? Shouldn't the instance variables be private, only accessible through messages?

like image 505
farhadf Avatar asked Jun 08 '09 20:06

farhadf


People also ask

What is instance variable in Obj C?

An instance variable is a variable that exists and holds its value for the life of the object. The memory used for instance variables is allocated when the object is first created (through alloc), and freed when the object is deallocated.

What is the purpose of an object's instance variables?

An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.

Can we define variable in header file in C?

Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.

Where are instance variables defined?

Instance variables are declared in a class, but outside a method, constructor or any block. When space is allocated for an object in the heap, a slot for each instance variable value is created.


2 Answers

The reason is so it can calculate offsets of variables for subclasses.

@interface Bird : NSObject {
    int wingspan;
}
@end
@interface Penguin : Bird {
    NSPoint nestLocation;
    Penguin *mate;
}
@end

Without knowing the structure of the "Bird" class, the "Penguin" class can't calculate the offset of its fields from the beginning of the structure. The penguin structure looks kind of like this:

struct Penguin {
    int refcount; // from NSObject
    int wingspan; // from Bird
    NSPoint nestLocation; // from Penguin
    Penguin *mate; // from Penguin
}

This has a side effect: if you change the size of a class in a library, you break all the subclasses in apps that link to that library. The new properties work around this problem.

like image 145
Dietrich Epp Avatar answered Oct 14 '22 07:10

Dietrich Epp


Although they are declared in the header file, all instance variable in Objective-C have @protected access by default. This means the variable is accessible within the class that declares it and any class inheriting from that class.

Here is Apple's documentation on defining an Objective-C class: Defining Classes

Notice the section titled "The Scope of Instance Variables".

like image 25
Nick Stamas Avatar answered Oct 14 '22 08:10

Nick Stamas