'MacOS: reading shared preferences in Swift and ObjectiveC
I have a project that mixes Swift and objective c. The controller for my preference panes is written in Swift. I can’t seem to read those preferences in Objective C.
This is the code that writes the parameter into the preferences…
let userDefaults = Preferences.shared.getUserDefaults()
@IBAction func DefType(_ sender: NSPopUpButton) {
var parameter:NSNumber
parameter = DefType.indexOfSelectedItem + 1 as NSNumber
userDefaults.set(parameter, forKey: ConstantUtility.StorageKeys.SelectedType.rawValue)
}
func getUserDefaults() -> UserDefaults {
return UserDefaults.standard
}
The above code is working as the following code is in the function that sets up the preference pane And it initiates the popup correctly.
func setupUI() {
var temp1:Int
temp1 = userDefaults.parameter(forKey: ConstantUtility.StorageKeys.SelectedType.rawValue) ?? 0
temp1 -= 1
DefType.selectItem(at: temp1)
}
On the other side of the program is the following code intended to read the preferences. This code always produces an answer of zero.
- (void) tableViewDoubleTapAction {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
long selectedType = [userDefaults integerForKey:@"SelectedType"];
I'm assuming the problem is in the objectiveC code but I'm open to changing either or both. Been spinning my wheels too long on this one.
Thanks in advance!
Solution 1:[1]
I set up a Preferences class as follows...
class Preferences : NSObject {
private override init() {}
@objc static let shared = Preferences()
@objc var selectedType: ConstantUtility.SelectedType {
get {
let type = UserDefaults.standard.integer(forKey: ConstantUtility.StorageKeys.SelectedType.rawValue)
guard type != 0, let selectedType = ConstantUtility.SelectedType(rawValue: type) else {
return ConstantUtility.SelectedType.One
}
return type
}
set {
UserDefaults.standard.set(newValue.rawValue, forKey: ConstantUtility.StorageKeys.SelectedType.rawValue)
}
}
the swift code to read the preference was changed to
temp1 = userDefaults.integer(forKey: ConstantUtility.StorageKeys.SelectedChart.rawValue)
And the Objective C code became
- (void) tableViewDoubleTapAction {
long selectedChartType = Preferences.shared.selectedType;
It is all working!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | trendsoft |
