Size of an NSArray

IosObjective CArrays

Ios Problem Overview


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

Ios Solutions


Solution 1 - Ios

int size = [array count];
NSLog(@"there are %d objects in the array", size);

Solution 2 - Ios

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"

Solution 3 - Ios

Size can be determined by sending 'count' to the NSArray instance, and printing to console can be done via NSLog(), eg:

NSArray * array = [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
NSLog(@"array size is %d", [array count]);

Solution 4 - Ios

Take a look at this post for your array size question

https://stackoverflow.com/questions/1530050/length-of-an-array-in-objective-c

Use NSLog to write to the console...

NSLog(@"The array size is %@", arraySize);

Solution 5 - Ios

In Swift 4

let a = ["a","b"]

a.count //2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlorentView Question on Stackoverflow
Solution 1 - IosAlex WayneView Answer on Stackoverflow
Solution 2 - IosDave DeLongView Answer on Stackoverflow
Solution 3 - IoscraftermView Answer on Stackoverflow
Solution 4 - IosChris WagnerView Answer on Stackoverflow
Solution 5 - IosgargView Answer on Stackoverflow