Using Pointers in Objective-C?

2019-09-06 06:09发布

问题:

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.