do I have to create a new object or can I use a method param?
So let's say I have this method that responds to a button event
- (void) myMethod: (id) sender
Is it better 开发者_如何学编程to use directly the function param?
NSLog(@"The sender tag is %d",sender.tag);
Or is it better to create a new object?
UIButton* myButton = (UIButton*) sender;
NSLog(@"The sender tag is %d",myButton.tag);
Why?
I've seen in tutorials that the preferred way in objective-c is the second one. But, in cases where you don't need to know the type of the sender and just access its properties/methods it should be Ok to use the first way. Am I missing something?
When you say UIButton* myButton = (UIButton*) sender;
, you are not making a new object. You are simply making a new handle (pointer) to the sender
object, and explicitly telling the compiler that it is a UIButton
.
This means that you can call UIButton
methods on it without having the compiler complain that they might not exist.
From a memory point of view, you should assume it makes no difference at all. The compiler is probably smart enough to not make you a new pointer anyway, and even if it did, it's going to be 4 bytes or so, which is not worth worrying about.
You're not missing anything and this isn't a particularly important issue. You have a few options:
NSLog(@"%d", sender.tag);
Sometimes that will produce warnings when compiling, depending on the type of the method parameter.
NSLog(@"%d", ((UIButton *)sender).tag);
Or finally:
UIButton *button = (UIButton *)sender;
NSLog(@"%d", button.tag);
(These all basically do the same thing, so it's mostly a matter of preference.)
If the sender is always UIButton, I would declare method as
- (void) myMethod: (UIButton*) sender
because it practically yield the same effect to pointer type casting. It also saves you one line of code.
精彩评论