views:

563

answers:

2

I'm getting my feet wet in Objective-C and Cocoa (I know, probably late, but hey I have to start somewhere) and I noticed that all objects are allocated out of the heap.

Is there any reason why this is the standard in Objective-C? I tried looked everywhere (and yes, even on StackOverflow), but I couldn't find any explicit reason, except "that is how it is". I'm especially keen because Objective-C is considered a strict super-set of C with OO features.

If I missed an article on the InterBlag or a post on StackOverflow by mistake on this topic, please initiate graceful shutdown. :)

+2  A: 

I think this owes to the Smalltalk heritage.

Also, you could say that stack-allocated objects are a peculiarity of C++. Very few other languages do that, and then mostly as a low-level optimization for the compiler. In C++ it's reasonable, since one of the stated goals was to be exactly as performant as plain C.

Why do you feel this is in conflict with the fact that Objective-C is a super-set of C? After all, plain C can't either allocate objects on the stack... nor anywhere. structs, OTOH, are allowed on the stack, both on C and Objective-C

Javier
"Plain C can't allocate objects on the stack... nor anywhere" Well I guess so, because there are NO objects (Well yeah, structs, and other hacks that can 'simulate' OO features...) Why I felt it was in conflict is only because C supports both stack and heap allocation, and so it was natural to assume C++ would do so for its objects, which it did. And so also Objective-C. But, nada. Anyway, I'm satisfied with your answer, but I'm holding back on the "Right-vote" to wait/encourage for other answers. :)
Suvesh Pratapa
A: 

I'm not exactly answering your question, but since you are understanding Obj-C's runtime, here it goes. You can allocate objects more efficiently using NSZones. You won't have them on the stack, but at least you can avoid some fragmentation and performance issues: link text

Marco Mustapic