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?
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.
+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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With