26

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?

andy
  • 8,775
  • 13
  • 77
  • 122
  • 1
    I pretty much use a pointer for everything but primitives. If it's an `int`, `NSInteger`, `CGFloat` or anything of that sort - I don't use an asterisk. Otherwise I give it the star. Though there's probably someone who can explain it better... – Aurum Aquila Feb 22 '11 at 05:33

1 Answers1

41

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.

Community
  • 1
  • 1
bbum
  • 162,346
  • 23
  • 271
  • 359
  • 2
    +1 thanks bbum, great answer. how do you know which types are primitive when working within the Cocoa framework. And more importantly, if do use a pointer incorrectly, will the mistake be caught at compile time? – andy Feb 22 '11 at 09:46
  • 6
    If you cmd-double-click something in Xcode, it should take you to the definition. If that definition is something like `Foo *bar` and you cmd-double-click the `Foo`, it'll take you to the definition of *that*. You'll quickly get a feel for which types are what. – bbum Feb 22 '11 at 16:55
  • Well put, bbum, I've always wondered this myself, and your explanation was very clear and to the point! +1 – Parker Jun 22 '13 at 00:21