3

I'm struggling a bit with some objective c syntax. Can someone please elaborate on the usage of * in the following instance method.

- (IBAction)sliderChanged:(id)sender{
    UISlider *slider = (UISlider *)sender;
}

I realize that we are creating a variable typed as UISlider and then setting it to sender once it is cast as a UISlider. However, I don't understand what the * are for and why

UISlider slider = (UISlider)sender; 

won't work.

user263097
  • 294
  • 1
  • 4
  • 15
  • This is a duplicate of http://stackoverflow.com/questions/2189212/. The answer on that question provides a great deal of Objective-C specific detail as to why this is the case. – bbum Apr 10 '10 at 20:03

4 Answers4

13

*, like in C, when used in a type denotes a pointer (such as your case) and to dereference a pointer.

A pointer is just a variable that contains the address in memory of something else, in your example a UISlider object.

So in your example,

UISlider *slider = (UISlider *)sender;

slider is of type UISlider *, or a pointer to a UISlider object.

The following tutorial about pointers in C also applies to Objective-C: Everything you need to know about pointers in C

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
cblades
  • 416
  • 3
  • 11
3

All Objective-C objects must be referenced using pointers because they live on the heap and not the stack.

Alex Rozanski
  • 37,815
  • 10
  • 68
  • 69
2

You are creating a variable called slider that has type UISlider* ie a pointer to a UISlider.

You are assigning the value of sender which is anid which is a pointer to an Objective C object to the variable slider so that slider and sender point to the same piece of memory.

In Apple's Objective C all objects are declared on the heap and are accessed through pointers.

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
  • Just to make sure I've got it.... After UISlider *slider = (UISlider *)sender; slider and sender would both be pointers to the same location in memory? – user263097 Apr 10 '10 at 19:43
  • Yes, you're right. It's important to keep in mind the difference between "objects residing in memory" and "pointers pointing to them". – Yuji Apr 10 '10 at 20:50
2

I think the confusion arises from the use of (id) in:

- (IBAction)sliderChanged:(id)sender{
    UISlider *slider = (UISlider *)sender;
}

Objective C has an id type that is more or less equivalent to (NSObject *). It can essentially point to any type of Objective C object. So, in reality that above code reads:

- (IBAction)sliderChanged:(NSObject*)sender{
    UISlider *slider = (UISlider *)sender;
}

More or less. Since we (the programmer) know that the sender object is an UISlider, we cast the object to a (UISlider*) when assigning its value to UISlider *slider.

Stephen Melvin
  • 3,696
  • 2
  • 27
  • 40