Objective-C and Pointers

后端 未结 3 842
死守一世寂寞
死守一世寂寞 2020-12-11 22:00

I understand pointers and know what they are and how to declare them. But, the problem is, none of the books, tutorials or guides actually explain why pointers are used.

3条回答
  •  悲哀的现实
    2020-12-11 22:36

    To add to the existing answers with some context: Objective-C is a strict superset of C. Quite a lot of the language is convention rather than syntax. For example, the use of 'dealloc' to do what a formal destructor does in other languages is just a convention of classes that inherit from NSObject. The compiler doesn't recognise your dealloc method as being in any way distinct from the others.

    One of the pragmatic decisions that allows objects to be grafted onto the C runtime is that they always live on the heap, never on the stack. The C mechanism for keeping track of something on the heap is a pointer. As a result, in Objective C you keep hold of all objects by pointer. The autorelease pool then ameliorates the syntactic burden that would result in cases where you really want to act like things are on the stack.

    So they're used to keep things on the heap, as already answered. And objects are kept on the heap because memory management relies on convention and because doing so allowed objects to be added to the C runtime with de minimis changes.

提交回复
热议问题