2014-11-30 6 views
1

Я пытаюсь создать элемент строки состояния в swift, чтобы я мог легко контролировать свою батарею, однако у меня есть ошибка Apple Match-O Linker (id) Error _NSVariableStatusItemLength. Вот некоторые скриншоты об ошибке:
Error1Apple Match-O Linker (id) Ошибка _NSVariableStatusItemLength

Здесь ошибка расширилась:
Error 2

И, наконец, вот мой код

import Cocoa 
func executeCommand(command: String, args: [String]) -> String { 

    let task = NSTask() 

    task.launchPath = command 
    task.arguments = args 

    let pipe = NSPipe() 
    task.standardOutput = pipe 
    task.launch() 

    let data = pipe.fileHandleForReading.readDataToEndOfFile() 
    let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)! 

    return output 

} 

extension Array { 
    func combine(separator: String) -> String{ 
     var str : String = "" 
     for (idx, item) in enumerate(self) { 
      str += "\(item)" 
      if idx < self.count-1 { 
       str += separator 
      } 
     } 
     return str 
    } 
} 

extension String{ 
    func replace(x:String,y:String) -> String{ 
     var z = self.stringByReplacingOccurrencesOfString(x, withString: y, options: NSStringCompareOptions.LiteralSearch, range: nil) 
     return z 
    } 
    func toUnformatedInt() -> Int{ 
     return (self.replace(",", y: "")).toInt()! 
    } 
    func split(delimiter:String) -> Array<String>{ 
     return self.componentsSeparatedByString(delimiter) 
    } 
} 

extension Int{ 
    func toFormatedStr() -> String{ 
     var i = 0 
     var Str = "" 
     for x in String(self){ 
      if i == 3{ 
       Str += ",\(x)" 
       i = 1 
      } else { 
       Str += "\(x)" 
       i += 1 
      } 
     } 
     return Str 
    } 
    func toStr() -> String{ 
     return String(self) 
    } 
} 

func get_key_and_value(string:String) -> Array<Any>{ 
    var x = string.split(" = ") 
    if x[1].toInt() != nil{ 
     return [x[0],x[1].toInt()!] 
    } else if x[1] == "Yes"{ 
     return [x[0],true] 
    } else if x[1] == "No"{ 
     return [x[0],false] 
    } else { 
     return [x[0],x[1]] 
    } 
    //return [return_val[0],return_val[1]] 
} 

class Battery{ 
    var battery = Dictionary<String, Any>() 
    init(){ 
     refreshValues() 
    } 
    internal func refreshValues(){ 
     let commandOutput:String = executeCommand("/usr/sbin/ioreg", ["-r","-w0","-cAppleSmartBattery"]) 
     var commandOutList = commandOutput.split("\n") 

     commandOutList.removeAtIndex(0) 
     commandOutList.removeAtIndex(0) 

     for _ in 1...5{ 
      var lastRemoved = commandOutList.removeLast() 
      if lastRemoved == "}"{ 
       break 
      } 
     } 

     //Got Needed Infomation Only 

     let commandOutStr = commandOutList.combine("") 
     let cmdOutStr = commandOutStr.replace("\"",y: "").replace(" ",y: "\n") 

     var cmdOutSplit = cmdOutStr.split("\n") 
     cmdOutSplit.removeAtIndex(0) 


     //var x = get_key_and_value(cmdOutSplit[0]) 
     //var key:String = x[0] as String 
     //var value = x[1] as Any 

     for x in cmdOutSplit{ 
      var y = get_key_and_value(x) 
      battery[(y[0] as String).replace(" ", y: "")] = y[1] as Any 
     } 
    } 
} 
@NSApplicationMain 


class AppDelegate: NSObject, NSApplicationDelegate { 
    @IBOutlet weak var window: NSWindow! 
    @IBOutlet weak var StatusMenu: NSMenu! 
    var statusItem: NSStatusItem?; 

    func applicationDidFinishLaunching(aNotification: NSNotification) { 
     let bar = NSStatusBar.systemStatusBar() 
     statusItem = bar.statusItemWithLength(CGFloat(NSVariableStatusItemLength)) 
     statusItem!.title = "Status Menu" 
     statusItem!.menu = StatusMenu 
     statusItem!.highlightMode = true 
    } 

    func applicationWillTerminate(aNotification: NSNotification) { 
     // Insert code here to tear down your application 
    } 


} 

Я попытался фиксируя проблему путем удаления директории DerivedData как было предложено, когда Павел ответил this question, однако это не помогло.

Редактировать: Спасибо @lemonmojo за то, что вы показываете, как создавать приложения-строки состояния!

ответ

1

Я только что узнал, как это исправить. Чтобы сделать меню, мне пришлось изменить код.

class AppDelegate: NSObject, NSApplicationDelegate { 
    @IBOutlet weak var window: NSWindow! 
    @IBOutlet var menu: NSMenu! 


    var statusItem: NSStatusItem!; 

    override func awakeFromNib() { 


    } 

    func applicationDidFinishLaunching(aNotification: NSNotification?) { 

     // Make a status bar that has variable length (as opposed to being a standard square size) 

     // This -1 should be 'NSVariableStatusItemLength' instead, but causes a link error 
     // PRODUCTION: Remind authors to check this before we leave early release - it may be fixed by Apple by then. 

     statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) 

     // Set the text that appears in the menu bar 
     statusItem.title = "My Item" 

     // Set the menu that should appear when the item is clicked 

     statusItem.menu = self.menu 

     // Set if the item should change colour when clicked 
     statusItem.highlightMode = true 

    } 

Я думаю, что это ошибка, потому что я должен был изменить statusItem = bar.statusItemWithLength(CGFloat(NSVariableStatusItemLength)) к statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
Благодаря тому, кто разместил эту статью на сайте this.

Смежные вопросы