【发布时间】:2016-02-08 01:27:59
【问题描述】:
对于具有持久状态的 OS X 应用程序,是否可以以编程方式检测应用程序上次打开、崩溃或意外关闭的时间? (所以我可以执行一些操作来确保应用程序处于一致状态)
【问题讨论】:
对于具有持久状态的 OS X 应用程序,是否可以以编程方式检测应用程序上次打开、崩溃或意外关闭的时间? (所以我可以执行一些操作来确保应用程序处于一致状态)
【问题讨论】:
您可以按照here 的描述使用NSSetUncaughtExceptionHandler。
NSSetUncaughtExceptionHandler { exception in
print("Exception: \(exception.name)
\(exception.reason!)
\(exception.description)")
print(exception.callStackSymbols)
}
我使用的代码是……
NSSetUncaughtExceptionHandler {
exception in
ExceptionManager.handle(exception)
}
而 ExceptionManager 类包括...
class ExceptionManager {
class func handle(exception: NSException) {
var exceptions = [ExceptionItem]()
if let items = NSUserDefaults.standardUserDefaults().arrayForKey("UncaughtExceptions") as? [NSData] {
for item in items {
if let exception = NSKeyedUnarchiver.unarchiveObjectWithData(item) as? ExceptionItem {
exceptions.append(exception)
}
}
}
let newItem = ExceptionItem(NSDate(), exception)
exceptions.insert(newItem, atIndex: 0)
if exceptions.count > 5 { // Only keep the last 5 exceptions
exceptions = Array(exceptions[0..<5])
}
var items = [NSData]()
for e in exceptions {
let item = NSKeyedArchiver.archivedDataWithRootObject(e) as NSData
items.append(item)
}
NSUserDefaults.standardUserDefaults().setObject(items, forKey: "UncaughtExceptions")
}
【讨论】: