Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of an NSArray

How do you get the size of an NSArray and print it in the console using NSLog?

like image 402
Florent Avatar asked Mar 24 '10 22:03

Florent


People also ask

What is an NSArray?

NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArrayRef . See Toll-Free Bridging for more information on toll-free bridging.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .


2 Answers

int size = [array count]; NSLog(@"there are %d objects in the array", size); 
like image 126
Alex Wayne Avatar answered Sep 21 '22 19:09

Alex Wayne


An answer to another answer:

You can't get the size of the array in megabytes, at least not without doing some tricky, unsupported* C voodoo. NSArray is a class cluster, which means we don't know how it's implemented internally. Indeed, the implementation used can change depending on how many items are in the array. Moreover, the size of the array is disjoint from the size of the objects the array references, since those objects live elsewhere on the heap. Even the structure that holds the object pointers isn't technically "part" of the array, since it isn't necessarily calloc'd right next to the actual NSArray on the heap.

If you want the size of the array struct itself, well that's apparently only 4 bytes:

NSLog(@"Size: %d", sizeof(NSArray)); 

Prints:

2010-03-24 20:08:33.334 EmptyFoundation[90062:a0f] Size: 4 

(Granted, that's not a decent representation, since NSArray is probably just an abstract interface for another kind of object, usually something like an NSCFArray. If you look in NSArray.h, you'll see that an NSArray has no instance variables. Pretty weird for something that's supposed to hold other objects, eh?)

* By "unsupported" I mean "not recommended", "delving into the inner mysticism of class clusters", and "undocumented and private API, if it even exists"

like image 37
Dave DeLong Avatar answered Sep 20 '22 19:09

Dave DeLong