Using Pointers in Objective-C?

2019-09-06 05:24发布

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.

4条回答
聊天终结者
2楼-- · 2019-09-06 05:59

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.

查看更多
混吃等死
3楼-- · 2019-09-06 06:01

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!

查看更多
Lonely孤独者°
4楼-- · 2019-09-06 06:04

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

Fantastic explanation on Mike Ash's blog here

查看更多
你好瞎i
5楼-- · 2019-09-06 06:17

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?).

查看更多
登录 后发表回答