Smart Home Smart Home - 1 year ago 75
iOS Question

Objective-C: Where is the pointer that corresponds to an instance variable of an object stored

Suppose I have the following class definition

@interface ClassX: NSObject
@property NSArray *arr;

Suppose I have the following lines in a method

ClassX *obj = [ClassX new];
obj.arr = [NSArray arrayWithObjects:[NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil]; //Edit to avoid getting derailed by differences due to @ notation

What is in the stack, what is in the heap?


obj in the stack. Value of this variable is the address of the place in the heap where obj resides.


Object of type ClassX

What about the NSArray and the NSNUmbers within the NSArray? Are they also divided as above? I.e The pointer to the NSArray is in the stack and the NSArray object is in the heap? If yes, what is contained in the heap memory that contains the "obj" object?

The figures I have seen are that this block of memory in the Heap contains a
pointer and then instance variables. The
pointer point to the location of the
Class structure
. I.e this piece of memory contains another isa pointer followed by
Method structs
. Each struct has a
and a
to where the corresponding implementation starts.

This seems to suggest that the area variable within the object is in the heap. I.e the pointer to the NSArray object is in the heap.

Based on answers below, is this a correct view of what is there in heap and stack?

The stack will contain 4 pointers, One to obj, one to NSArray, two to NSNumber objects.

The heap memory that starts at the address pointed to by
1. the
pointing ClassX class structure
2. Followed by memory to store NSArray object.

This NSArray object memory has
1. isapointer pointing to NSArray class structure
2. followed by memory to store 2 NSNumber objects.

The NSNUmber object memory contain
1. A isapointer pointing to NSNumber class structure
2. Followed by memory to store 2 ints

Answer Source

Both NSArray and NSNumber objects are heap-allocated, not stack-allocated.

They do not look like heap objects because compiler hides it from you using the new relatively syntax with @.

When you write

@[@1, @2]

The compiler translates it to

[NSArray arrayWithObjects: [NSNumber numberWithInt:1], [NSNumber numberWithInt:2]]

The end result is as follows: the stack has a pointer to an object of type ClassX. The memory pointed to by this pointer starts with an isapointer, followed by a pointer to another location in the heap that has NSArrray object in it. In turn, this part of heap memory has another isapointer followed by a pointer to a block of memory representing the inner array of NSArray, containing two pointers to NSNUmber objects. Each of NSNumber objects has an isapointer followed by data which represents the number.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download