Milesh
Milesh

Reputation: 271

Size of NSArray

When I tried to check the size of NSArray which is declared without any capacity, I found it 4. Now the question is why it is always 4? please help me out to find it.... Thanks

Upvotes: 8

Views: 15274

Answers (2)

bbum
bbum

Reputation: 162722

Given this:

NSArray *foo;
NSLog(@"%d", sizeof(foo));

You'll either get 4 or 8, depending on if you are on a 32 or 64 bit system. Note that I quite purposefully didn't initialize foo; there is no need to do so as sizeof(foo) is giving the bytesize of foo and foo is just a random pointer to an object. Wouldn't matter if that were id foo; void*foo; NSString*foo; all would be 4 or 8.

If you want the allocated size of an instance of a particular class, the Objective-C runtime provides introspection API that can do exactly that. However, I can't really think of any reason why that would be more than passingly interesting in a program.

Note that the allocation size of an instance does not account for any sub-allocations. I.e. an NSArray likely has a backing store which is a separate allocation.

To reiterate:

sizeof(foo) in the above code has nothing to do with the size of the allocated instance.

Upvotes: 6

Chuck
Chuck

Reputation: 237110

If you're talking about sizeof, it is not the right way to find out how much data an NSArray is holding. Objective-C objects are always accessed through pointers, and the size of a pointer on the iPhone is 4 bytes. That's what sizeof is telling you. To find out how many objects are in an array, ask the array for its count.

Upvotes: 13

Related Questions