2

I have a Cache System for iOS, and I want to add a function to log memory usage for a list of objects.
so how to calculate memory usage of custom object?

xhan
  • 6,057
  • 4
  • 33
  • 47
  • I think you can find the answer [here](http://stackoverflow.com/questions/5895971/using-sizeof-equivalent-in-objective-c) – Xav Aug 24 '11 at 09:23
  • @Xav, why don't you post that as answer? – Rudy Velthuis Aug 24 '11 at 10:54
  • 1
    thanks @Xav , the article about objc runtime is really interesting. – xhan Aug 24 '11 at 16:26
  • @Rudy SO translates my one-line answers into comments so I just do comments by default when it's a one-liner. Feel free to upvote ;-) – Xav Aug 25 '11 at 14:27

2 Answers2

2

You are in for allot of work. Using class_getInstanceSize() will get you the instance size for one objects, but not for the objects that objects refers to. Each object reference will only count as a 4 byte pointer, not the actual instance size of the refereed object.

You could be clever and use class_copyIvarList(), traverse the ivars and ask any ivar that is an object for it's instance size as well, then recursively do the same for your superclass until you hit the root class.

Or you could just fire up Instruments with the memory allocations template, and measure the actual memory usage in real time.

PeyloW
  • 36,742
  • 12
  • 80
  • 99
  • seems a tough work. and also I need to check whether the object is already calculated before – xhan Aug 24 '11 at 16:24
1

look for the class_getInstanceSize() function in the Obj-C runtime.

NSResponder
  • 16,861
  • 7
  • 32
  • 46