Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-C: Why interface type can't be statically allocated?

NSString s1;   //compile error: interface type cannot be statically allocated
NSString *s2   //good

Statically would mean the memory for that object is allocated at compile-time? But what is the reason behind allocating all objects at runtime and access through pointers? I know that pointers allow a better use of memory, for example passing them as method's parameters but why forbid static allocation? I'm new to this language, I'd like to understand its vision.

like image 260
user3290180 Avatar asked Nov 01 '25 04:11

user3290180


1 Answers

In C++ you can't have polymorphic objects unless you have a pointer to that object. Objective-C doesn't let you open that can of worms. It's a dynamically typed language (with a lot of protection if you want) - and locking in your type at compile time goes against the philosophy of the language.

NSString *s2 = [[NSString alloc] initWith ???];

consider that line. You're allocating a string object (I left the details of the constructor blank on purpose). You won't get an actual instance of NSString - the type of your object will be a private subclass. This concept is called Class Clusters.

https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html

Depending on what constructor is run, and what parameters are passed in could affect what your runtime type is. This would not be possible with a statically allocated object.

There is of course, a lot more to your question, but consider all that is possible given every object is dynamic at runtime. Also consider the complexity of C++ that this avoids.

like image 92
KirkSpaziani Avatar answered Nov 04 '25 10:11

KirkSpaziani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!