SMCopyAllJobDictionaries and SMJobCopyDictionary is deprecated, so what are their substitutions?

前端 未结 1 442
天命终不由人
天命终不由人 2021-02-13 17:34

I use SMCopyAllJobDictionaries and SMJobCopyDictionary to check whether app is Login Item in Mac, but in 10.10, they are deprecated. So what are their

1条回答
  •  我寻月下人不归
    2021-02-13 17:46

    You don't need a replacement. Just use SMLoginItemSetEnabled, if it succeeds, store the value in NSUserDefaults. Every time the app launches, call SMLoginItemSetEnabled with the stored value from your NSUserDefaults to check if something changed. If it returns false, set your user defaults value accordingly, otherwise the status is still the same one you previously remembered in your NSUserDefaults.

    Example:

    import Foundation
    import ServiceManagement
    
    final class LoginItem {
    
        let identifier: String
    
        private let nc = NSUserDefaults.standardUserDefaults()
    
        init(identifier: String) {
            self.identifier = identifier
        }
    
        var enabled: Bool {
            return nc.boolForKey(defaultKey)
        }
    
        func setEnabled(enabled: Bool) -> Bool {
            if SMLoginItemSetEnabled(identifier, enabled) {
                nc.setBool(enabled, forKey: defaultKey)
                return true
            }
            return false
        }
    
        func validate() -> Bool {
            if setEnabled(enabled) {
                return true
            }
            nc.removeObjectForKey(defaultKey)
            return false
        }
    
        private var defaultKey: String {
            return "SMLoginItem-" + identifier
        }
    }
    

    Just call validate on startup to validate the on/off state.

    0 讨论(0)
提交回复
热议问题