How does sender.selected = ! sender.selected toggle between selected states?

元气小坏坏 提交于 2019-12-23 03:26:11

问题


I'm very new to Objective-C so sorry if this is extremely obvious to many of you, but I'm trying to work out how the following piece of code is actually working:

- (IBAction)chooseColour:(UIButton *)sender {
 sender.selected = !sender.isSelected;
}

Now it obviously toggles between the selected and unselected states of the button sending the action, but what is the code 'sender.selected = !sender.isSelected' actually saying? Is it just 'set the sender selected property to the opposite (i.e. ! not) of the getter'? So if the getter is 'getting' the current selected value as true then it sets the selected property as !true i.e false. Or is this a piece of convenience code that I'm not yet privy to? Because it also seems that '!sender.isSelected' simply means not selected as in

if (!sender.isSelected){
statement
}

i.e. do statement if the sender is not selected. This is no doubt really obvious, just I'm a bit confused with it at the moment.

Thanks!


回答1:


You are entirely correct, it's calling the getter to obtain the value and calling the setter with the NOT (!) of the value. It isn't Objective-C, it's plain C syntax.




回答2:


Is it just 'set the sender selected property to the opposite (i.e. ! not) of the getter'?

Exactly. That.

Or is this a piece of convenience code that I'm not yet privy to?

No, the only piece of syntactic sugar is the dot notation for getters/setters, but you are already aware of it.




回答3:


The portion of the code:

sender.selected = !sender.isSelected;

Basically inverts the selection. It asks the question Is this false? so true evaluates false, and false evaluates to true. So it's a toggle.




回答4:


from documentation :

@property(nonatomic,getter=isSelected) BOOL selected;                                // default is NO may be used by some subclasses or by application

//explanation if you use ![sender isSelected] value in property isn't changed. then if you use setter sender.selected = ![sender isSelected] - new value is set to the sender (selected property). then run getter sender isSelected return new value, uff i hope it helps



来源:https://stackoverflow.com/questions/18243921/how-does-sender-selected-sender-selected-toggle-between-selected-states

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!