tags:

views:

128

answers:

4

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.

+2  A: 

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

Perspx
+2  A: 

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.

Mark
Just to make sure I've got it....AfterUISlider *slider = (UISlider *)sender;slider and sender would both be pointers to the same location in memory?
Yes, you're right. It's important to keep in mind the difference between "objects residing in memory" and "pointers pointing to them".
Yuji
+11  A: 

*, 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

cblades
+1  A: 

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.

Steve Melvin