Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to and when not to use pointers in Objective-C

I know there are a lot of questions on pointers out there, particularly now for Objective-C. But I'm looking for some higher level answers to help me understand the paradigms in Objective-C.

I've heard some people say that using pointers in Objective-C is a matter or experience, i.e. some classes demand that you use pointers, others don't. Is this true? And is that the extent of using pointers in Objective-C.

Basically, apart from when you want to explicitly pass reference variable to methods, what are the rules for pointers in Objective-C?

like image 600
andy Avatar asked Feb 22 '11 05:02

andy


1 Answers

You use a pointer always when referring to something on the heap and sometimes, but usually not when referring to something on the stack.

Since Objective-C objects are always allocated on the heap (with the exception of Blocks, but that is orthogonal to this discussion), you always use pointers to Objective-C objects. Both the id and Class types are really pointers.

Where you don't use pointers are for certain primitive types and simple structures. NSPoint, NSRange, int, NSUInteger, etc... are all typically accessed via the stack and typically you do not use pointers.

As for Why the * in Objective-C?, you might find this question of interest.

like image 198
bbum Avatar answered Oct 22 '22 03:10

bbum