Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total Size of NSMutableArray object

People also ask

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 is NSMutableArray Objective C?

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 . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .

Is NSMutableArray thread safe?

In general, the collection classes (for example, NSMutableArray , NSMutableDictionary ) are not thread-safe when mutations are concerned. That is, if one or more threads are changing the same array, problems can occur.

What is 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.


To get the number of objects in the array, use

[temp count]

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


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 note that this will only count the memory size of the ivars declared in each class.


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


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


Well, you could do something like:

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

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

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