Using Pointers in Objective-C?

。_饼干妹妹 提交于 2019-12-25 02:40:21

问题


Whenever Apple creates its own custom classes, it often creates a pointer to the object instead of the actual object itself.

For example, instead of doing:

Class object

They often do:

Class *object = [[Class alloc] init];

Why are pointers so commonly used instead of putting the object on the stack? Is there some technical reason for this, because I don't see any immediate benefit of doing so.

EDIT: If Objective-C doesn't support objects on the stack how can they create any non-pointers? I mean I have seen people use NSInteger directly.


回答1:


Objective-C doesn't support objects on the stack.

Fantastic explanation on Mike Ash's blog here




回答2:


Objective-C regular usage make objects travel all over the place, they can be accessed, modified and managed from a million different places. Stack objects, by definition have only one owner and their life and availability is restricted to the function (thread) that spawned them. This would be a major problem in Obj-C since either the object lifespan would not be controlled, or the object lifespan would be the same as the application (have you seen how much memory those objects take?).




回答3:


The * (pointer) points to a spot in memory that this object is going to be saved to. Also, This is just the way that objective-c is written. Plus i believe that objective c doesnt allow you to put the object on the stack!




回答4:


if the object is passed around a lot it may be easier to use a pointer than passing a reference. When you know you are passing a pointer it indicates that things might get modified where as a pass by reference may be overlooked and cause things to change when you didn't want them to.



来源:https://stackoverflow.com/questions/9123079/using-pointers-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!