(id)sender iPhone Explanation - iphone

Hey guys,
can anyone explain me what (id)sender exactly means? I have seen it in so many actions and I don't know how to set this sender id.
- (IBAction)publishStream:(id)sender {
// do something
}
Furthermore, can you tell me how I can set this sender id in code?
Thanks, Cheers, doonot

'id' is a type -- specifically, it's the type of an untyped pointer to an object. A variable of type 'id' can point to any objective-c object. In the case of an IBAction, it's common to have a single parameter named 'sender' that is the object sending the action. Any type of object can send the action, so the type of the 'sender' parameter is 'id'.

Using that you can re-direct several ui "widgets" to the same handler function. You can then use the "sender" to know which one generated the message.

Well an ID is basically a blank type, so it's whatever type of object that called it, I don't believe that you actually set the sender, it's just the object. So say a UIButton called my IBAction, then whatever the UIButton happens to be will be the sender.

actually, sender is Control which invoke the event.
like,
if if you TouchInside the button and you had attached to your method.
then that button will be sender here.

Related

reaching the 'tag' property of sender object

I have created an IBAction like this: -(IBAction) buttonTapped:(id)sender; and connected it to a UIButton using interface builder, the problem is that I can't do something like NSLog(#"%d",sender.tag); the compiler gives me syntax error that the tag property does not exist in object of type id ... but however when I do something like NSLog(#"%#", sender); the console displays info about the button and its tag ... so the question is: how can I reach the tag property of the UIButton through the sender object ?
Have you tried casting sender? For example:
NSLog(#"%d", ((UIButton *)sender).tag);
You have to cast it, because the compiler does not know the type of object (hence the id type), but the runtime will know.
So, it's similar to :
NSLog(#"%d", [(UIButton*)sender tag]);
Instead of casting, it often makes for cleaner code just to be more specific in your action declaration:
-(IBAction) buttonTapped:(UIButton*)sender;
You can use UIButton, UIControl, UIView or whatever level of specificity you require.

Can someone tell me the difference between the call in IOS

I have a method called Display. Can somebody explain me the difference of calling the same method in the following two ways.
[self Display];
[self performselector:#selector(Display)]
- (void)Display {
NSlog(#"Data");
}
both are basically the same with one minute difference.. #selector gives a name to your method which you can pass around as an attribute to other objects or in other function calls.
Like if you want to send a message to other object and you want to send display as an attribute then you will have to give it a name using #selector and thus you can send it.. its a pretty vague concept.. hope this helps.
and to quote apple documents...
"However, the performSelector: method allows you to send messages that
aren’t determined until runtime. A variable selector can be passed as
the argument:
SEL myMethod = findTheAppropriateSelectorForTheCurrentSituation();
[anObject performSelector:myMethod];
The aSelector argument should identify a method that takes no
arguments. For methods that return anything other than an object, use
NSInvocation."
[self Display] is shorter and easier to read, write and comprehend.
[self performSelector:#selector(Display)] makes it possible to execute arbitrary selectors. If you save the selector in a variable, then you can execute it later on without knowing the method you invoke. It is therefore more flexible. Even better: you can pass selectors and objects to other objects and let them invoke it for you when necessary. An example why you want to use this is the NSUndoManager which simple invokes a selector to undo an action if the user executes the Undo command.
I do not think that there is a big difference between examples you provided, but perform selector is very useful when you for instance wanna move execution of your method to the background thread.
[self Display]; is a call to a known method on a known object.
It's easy to give it some params if your want : [self DisplayWithParam1:(NSString*)aString param2:(int)aNumber param3:(NSDictionary*)aDict
[self performselector:#selector(Display)] is a call that allows you to call a possibly not known method on a possibly not known object type.
Let's imagine you have many kind of classes that all respond to a given protocol that require to have the Display method implemented. You put some objects of thoses different classes in an NSMutableArray. When parsing the array later, you will get id typed objects.
So calling[myArrayObject Display]; will work at runtime but will generate a warning at compile time as id does not support any method of course, even if you know that this object supports the method.
To prevent thoses warning, call [myArrayObject performselector:#selector(Display)];.
The problem with that call is that is harder to pass some parameters.
performSelector:withObject:withObject:
Sends a message to the receiver with two objects as arguments.
- (id)performSelector:(SEL)aSelector withObject:(id)anObject withObject:(id)anotherObject
Parameters
aSelector
A selector identifying the message to send. If aSelector is NULL, an NSInvalidArgumentException is raised.
anObject
An object that is the first argument of the message.
anotherObject
An object that is the second argument of the message
Return Value
An object that is the result of the message.
Discussion
This method is the same as performSelector: except that you can supply two arguments for aSelector. aSelector should identify a method that can take two arguments of type id. For methods with other argument types and return values, use NSInvocation.
Availability
Available in Mac OS X v10.0 and later.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocSelectors.html
The #select call is faster. Generally the uglier (and less dynamic) the code you have in Objective-C, the faster it runs. Here, the selector call bypasses the usual call to objc_msgSend().
I wouldn't recommend writing code like this if you can avoid it. Selectors are somewhat common in Cocoa, but if you're using it for a speedup it's really not worth it. objc_msgSend() is highly optimized and very fast.

objective-c : what does these code snips mean?

I am new to iphone development and just in learning phase. I am learning from books and Video lectures while I saw this code Which I am unable to understand
- (IBAction)logoff:(id)sender {
//some code here
}
here I do not understand that is id a data type or some entity. and what could be the reason to pass id as argument.
and at anohter place I saw
if(self)
{
// some code
}
I do not understand why he pass self in if. what the reason to check self. Should we check self before any time we use it.
Please it would be more helpful for me if you tell the reason that why he use this so that I could you it in my codes efficiently and reasonably.
thanks
- (IBAction)logoff:(id)sender {
//some code here
}
Lots of controls (UIButton, UISwitch, UIBarButtonItem) can be connected to the same action method. Because the sender is of type id it will accept lots of different sender types, i.e. the sender type isn't restricted to only a UIButton.
Maulik's remark that the argument represents the tag is wrong, it represents the object (e.g. a UIControl) that sent the message. The object can be typecasted though in order to retrieve the tag, provided the type to which the sender is casted to contains the tag property and the sender is of the correct type.
Now about your other question: self is checked to be not nil before proceeding. Sometimes initialization can fail for several reasons (e.g. memory issues). If the object failed to initialize properly there's not much you can do with it (no access to ivars for example, since no memory was allocated for the ivars).
He doesn't, he evaluates self to check if it is nil.
Meaning if self is not nil do // some code
This means that logoff contains id as the argument to function.. now in if condition it checks that the control still exists or not... It happens that you may just release the control or just get released by itself due to your logics... So we need this to check that control still exists..
- (IBAction)logoff:(id)sender {
//some code here
}
the above code is for a button click.A button(logoff) that is putted via IB.When your click that button, method is associate with that button and will get called. (id)sender is an argument that represent the button's tag property.This is useful in case where you have more then one button and you want to handle the click events of those buttons.
if(self)
{
// some code
}
The above code checks weather memory allocation is done properly or not.

Question about Objective-C selectors; Can I use parameters and how?

I'm attempting to use a selector with arguments and failing while doing so. I'm coming from C/++ and selectors are a tad bit confusing. I have this code:
playItem = [CCMenuItemLabel itemWithLabel:playLabel target:self selector:#selector(goToScene:)argumentHere];
How would I go about passing an argument to a method in this way?
Thanks in advance:D
You can't. Selectors specify only method to be invoked, not parameters to be passed.
What you can do, is to check sender parameter in your goToScene: method. It's gonna be the element on which action is performed (most probably CCMenuItemLabel in your case).
Thus, you can see which element was invoked (if you use goToScene: for several ui elements) and decide which 'parameter' to use.
To tell different ui elements apart, tag attribute is often used. So, code could look like
if ([sender tag] == 1) {
...
} else if ...
If you don't like too many ifs, lookup table will work.
Are you maybe looking for performSelector:withObject? I'm afraid I don't quite understand your questions maybe.
Nikita is right, when you are setting up the selector you just pass in the descriptor name. Later in your code, when you call the method, you will pass in any arguments.

iPhone - how to pass an object to a button action

I have to pass an object to an button's action... something like
[myButton addTarget:self action:#selector(sendIt:MY_OBJECT) forControlEvents:UIControlEventTouchDown];
I cannot set a variable and use that on the method because I am on a static class.
How do I do that?
You cannot, the signature of an button's action is always*) -(IBAction)methodToCall:(id)sender where sender is your button, or whatever is calling the action.
I cannot set a variable and use that on the method because I am on a static class.
I am not sure what you mean with this.
*) There are a couple of other signatures new on the iPhone compared to the Mac, but none of those allow passing objects either.
The UIButton cannot pass object to event selector. You can use the property tag example:
myButton.tag = SOMEBUTTON_ID;
Also you can cast pointer to you object to NSInteger and assign it to tag property, but this technique does not solve problem of the lifetime of the object and in the future, such code may stop working.
I discovered a way to do that.
You create a class of UIButton and inside the class you declare a public variable that corresponds to the type of object you want to pass.
When you create the button you use that class and store the object inside its property.
then when the button is clicked you retrieve the ID, retrieve the button and the object stored inside it.
Now you have the object...