How to get the value of a UISwitch?

霸气de小男生 提交于 2019-12-03 23:53:02
Joel Kravets

To save it

[newContact setObject:[NSNumber numberWithBool:important.on] forKey:@"important"]; 

To retrieve it

BOOL on = [[newContact objectForKey:@"important"] boolValue];

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]

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"];

I used

[NSString stringWithFormat:@"%d",(self.allNotificationSwitch.isOn ? 0:1)];

And

[NSString stringWithFormat:@"%@",(self.allNotificationSwitch.isOn ? @"Yes":@"No")];
[newContact setBool:[NSNumber numberWithBool:important.on] forKey:@"important"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!