为什么我们在iphone中创建的大多数对象都是指针 [英] why most of the objects we create in iphone are pointers

查看:108
本文介绍了为什么我们在iphone中创建的大多数对象都是指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们在iphone中创建的大多数对象都是指针..?
就像我创建NSString * str,NSMutableDictionary * dict .. etc

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

推荐答案

简答

因为Objective-C对象只能在堆上分配并作为指针进行操作。

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

长答案

Objective-C要求在堆上分配类并作为指针进行操作,因为多态需要使用指针,因为指向接口的指针总是具有相同的大小,而不同的实现界面可能有不同的大小。在C ++中,可以为类使用自动(堆栈)和动态(堆)存储;但是,在前一种情况下,必须要注意切片(当派生类型被分配给基类型时,导致对象丢失使其成为派生类型而不是基类型的内容),并且仅使用指针Obj-C消除了这个潜在的陷阱。此外,允许堆栈分配的对象使Objective-C具有的引用计数方案变得复杂,并且由于堆栈分配的对象仅存在于创建它们的范围内,因此无论如何通常在堆上分配对象,因此支持对象作为堆栈分配值将是边际效益。作为旁注,我还应该提到在Java和C#中,对象同样被限制为仅堆分配。

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.

这篇关于为什么我们在iphone中创建的大多数对象都是指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆