[ACCEPTED]-Total Size of NSMutableArray object-nsmutablearray

Accepted answer
Score: 105

To get the number of objects in the array, use

[temp count]

If 6 you want the total memory usage of the array, you'll 5 have to loop through and add up how much 4 memory each object uses, but I don't think 3 that a generic object will give you its 2 size. In general, you shouldn't really have 1 to worry about memory usage, though.

Score: 8
size_t size = class_getInstanceSize([temp Class]);
for (id obj in temp) {
    size += class_getInstanceSize([obj Class]);
}

Note that class_getInstanceSize is declared in /usr/include/objc/runtime.h

Also 2 note that this will only count the memory 1 size of the ivars declared in each class.

Score: 5

There is no direct way to do this since 4 all objects are just stored by reference. There 3 is no concrete notion of "size" in cocoa, especially 2 since objects can have multiple owners which 1 might lead to double counting or other problems.

Score: 4

If the NSArray, and all the objects it contains, and 5 all their sub-objects (recursively etc.) respond 4 to NSCoder, you might be able to serialize 3 the array into a temporary NSData memory 2 chunk, and then get the memory size of that 1 one flat temporary object.

Score: 2

Well, you could do something like:

size_t total;
id obj;
for (obj in temp)
  {
  total += class_getInstanceSize([obj class]);
  }

but that 11 doesn't tell you exactly how much storage the array 10 is actually using, since it can grow dynamically 9 and might have more memory at any given 8 time than it needs for just the objects 7 it's pointing to, and of course you'd have 6 to deal with any collections recursively.

If 5 you're trying to get an idea of how much 4 memory you're using, I suggest digging into 3 the tutorials for Instruments, and getting 2 your head around the memory usage probes 1 it provids.

More Related questions