Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

objective c - why most of the objects we create in iphone are pointers

why most of the objects we create in iphone are pointers..? like i create NSString *str, NSMutableDictionary *dict.. etc

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Short Answer
Because Objective-C objects can only be allocated on the heap and manipulated as pointers.

Long Answer
Objective-C requires that classes be allocated on the heap and manipulated as pointers, because polymorphism requires the use of pointers, since the pointer to an interface will always have the same size, while different implementations of the interface may have different sizes. In C++, one can use both automatic (stack) and dynamic (heap) storage for classes; however, in the former case, one must beware of slicing (when a derived type is assigned to a base type, resulting in the object losing the content that makes it the derived type instead of the base type), and using pointers only as in Obj-C eliminates this potential pitfall. Additionally, allowing stack-allocated objects complicates the reference counting scheme that Objective-C has in place, and since stack-allocated objects live only in the scope in which they are created, one usually allocates objects on the heap, anyway, and so there would be marginal benefit in supporting objects as stack-allocated values. As a side note, I should also mention that both in Java and in C#, objects are similarly constrained to heap only allocation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...