Suppose I have the following class definition
@interface ClassX: NSObject
@property NSArray *arr;
@end
Suppose I have the following lines in a method
-(void)someMethod
{
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?
Stack:
obj in the stack. Value of this variable is the address of the place in the heap where obj resides.
Heap:
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 isa
pointer and then instance variables. The isa
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 selector
and a pointer
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.
EDIT 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 obj
has
1. the isapointer
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
obj.arr
will contain a reference to the static array in this data section.obj
will be in the heap. - Paulw11Edit
in the question above. Can you take a look? - Smart Home