Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective-C, how does +alloc know how much memory to allocate?

Let's say I have a class declared as:

@class SomeClass

@interface SomeClass: NSObject {
  NSString *myString;
  NSString *yourString;
}

@end

And later, in some other code I say:

SomeClass *myClass = [[SomeClass alloc] init];

How does SomeClass know how much memory to allocate given that it didn't override +alloc? Presumably it needs storage for the ivars myString and yourString, but it's using +alloc inherited from NSObject. Is there reference material that covers these details?

like image 278
Rob Jones Avatar asked Sep 03 '09 02:09

Rob Jones


People also ask

What does Alloc mean in Objective C?

alloc: short for allocation, reservers a memory location and returns the pointer to that memory location. This pointer is then stored in the k variable. init: short for initialization, sets up the object and returns the object.


1 Answers

+alloc is just a class method like any other. The default implementation in NSObject, uses class_getInstanceSize() to get the instance size that should be allocated. The instance size is determined based upon a combination of per-class (without inheritance) compile time structure size and per-runtime calculation of total size of the class and all superclasses. This is how non-fragile iVars are possible in 64 bit and the iPhone runtimes.

Some classes, class clusters in particular, don't actually do the true instance allocation until the initializer is called (which is why it is important to do self = [super init] in your initializer methods).

like image 103
bbum Avatar answered Sep 17 '22 19:09

bbum