问题
I am a newbie iOS programmer and I have a problem.
I currently work on iOS Core Data and my problem is that I want to insert data into a boolean attribute to a database by taking the value of a UISwitch
.
The problem is that i don't know what it the method i have to call (e.g .text does the same thing but for UITextField). I have done a small google search but no results. Here is some code:
[newContact setValue:howMany.text forKey:@"quantity"];
[newContact setValue:important.??? forKey:@"important"];
howmany is a textfield, important is a UISwitch
回答1:
To save it
[newContact setObject:[NSNumber numberWithBool:important.on] forKey:@"important"];
To retrieve it
BOOL on = [[newContact objectForKey:@"important"] boolValue];
回答2:
Have you looked at the docs for UISwitch
? Generally ou should make the docs your first point of call when searching for information, then turn to google and then to stack overflow if you really can't find what your after.
You want the @property(nonatomic, getter=isOn) BOOL on
property like:
important.isOn
If you haven't got Core Data set to use primitives you may have to wrap that boolean in an NSNumber
:
[NSNumber numberWithBool:important.isOn]
回答3:
The other posters are correct that you need to use the isOn method to get the value, however this returns a BOOL value, which you can't pass directly to setValue:forKey because that method expects an object.
To set the value on your core data object, first wrap it in an NSNumber, like this:
NSNumber *value = [NSNumber numberWithBool:important.on];
[newContact setValue:value forKey:@"important"];
回答4:
I used
[NSString stringWithFormat:@"%d",(self.allNotificationSwitch.isOn ? 0:1)];
And
[NSString stringWithFormat:@"%@",(self.allNotificationSwitch.isOn ? @"Yes":@"No")];
回答5:
[newContact setBool:[NSNumber numberWithBool:important.on] forKey:@"important"];
来源:https://stackoverflow.com/questions/9218931/how-to-get-the-value-of-a-uiswitch