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开发者_如何学JAVA is why it is always 4? please help me out to find it.... Thanks
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
.
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:
精彩评论