Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

ryans79

macrumors regular
Original poster
Apr 12, 2009
226
0
Hello,
My Obj-C theory is not as good as it should be, i have just started on Obj-C and xCode/IB, although i can work with these and use these statements/commands , i would like to know what its actually doing.

-(IBAction)sliderChanged: (id)sender
{

This is the line thats bit confusing to me (theory wise):

UISlider *slider = (UISlider *)sender;

in the first part
UISlider *slider
I see that we have assigned a new pointer called "slider", and i know this is a convenience method so i dont have to use alloc, but why do we use this
(UISlider *)sender
in the second part?

that second "*" is whats kind of throwing me.



°° ryan
 
weell, that's a little complicated.
what you have to know: type "id" actually means "can be anything". in your case you seem to know that "sender" (which is of type id, so it can be anything) is actually an UISlider object.
if you would write
UISlider *slider = sender;
you would get an error, because you are trying to assign an object of type "id" to an object of type "UISlider". Because they are not the same type, that will not work. what
(UISlider *)sender
does is convert sender (type id) to an object of type UISlider. this only works if sender actually IS an UISlider-object, but if you know it is, then it'll work. so
(UISlider *)sender
simply returns "sender" as an UISlider-object, which is then assigned to your newly created pointer.

hope I could explain it :D

and btw: you are never, at any point, using convenience methods here. convenience methods are methods that return newly created objects! sender is not created anywhere in your method. it already exists. a convenience method would be something like that:
[NSString stringWithString:mad:"something"];
which returns an autoreleased object, while a method using alloc and init is:
[[NSString alloc] initWithString:mad:"something"];
which returns a new object that is not autoreleased.
 
I see, thanks for the explanation, its not totally clear to me, but it does make sense.

and btw: you are never, at any point, using convenience methods here.
...

Damn, now i'm confused when to use alloc/retain :( :confused:
I guess I started on the book "Beginning iPhone Development" (recommended by another kind person here) a little too soon :(
 
To add, the code you show is a type cast. There is no real conversion going on. In this case it's an assignment where the bits of the slider variable are set to the bits of the sender variable. But the type of the slider variable is different from the type of the sender variable.

You can google for type cast or look it up on wikipedia or any book on the C language.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.