Using * in Objective C Syntax

I am struggling a bit with some objective c syntax. Can someone comment on the use of * in the next instance method.

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

      

I understand that we are creating a variable printed as UISlider and then setting it to the sender as soon as it shows up as a UISlider. However, I don't understand what the * is for and why

UISlider slider = (UISlider)sender; 

      

will not work.

+2


source to share


4 answers


*, as in C, when used in a type denotes a pointer (like your case) and dereferences the pointer.

A pointer is just a variable holding the memory address 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 guide to pointers in C also applies to Objective-C: Everything you need to know about pointers in C

+13


source


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



+3


source


You create a variable named slider that is of type UISlider *, that is, a pointer to a UISlider.

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

In Apple Objective C, all objects are declared on the heap and are accessible via pointers.

+2


source


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

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

      

Objective C is of type id , which is more or less equivalent to (NSObject *). It can essentially point to any Objective C object. So, actually, what the above code reads:

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

      

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

+2


source







All Articles