我正在尝试在后台进程中运行一个程序,该程序将注册系统中的每个关闭事件。
通过注册 NSWorkspaceWillPowerOffNotification 来实现此目的,如下所示:
#import <AppKit/AppKit.h>
@interface ShutDownHandler : NSObject <NSApplicationDelegate>
- (void)computerWillShutDownNotification:(NSNotification *)notification;
@end
int main(int argc, char* argv[]) {
NSNotificationCenter *notCenter;
notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
ShutDownHandler* sdh = [ShutDownHandler new];
[NSApplication sharedApplication].delegate = sdh;
[notCenter addObserver:sdh
selector:@selector(computerWillShutDownNotification:)
name:NSWorkspaceWillPowerOffNotification
object:nil];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[[NSFileManager defaultManager] createFileAtPath:@"./output.txt" contents:nil attributes:nil];
});
[[NSRunLoop currentRunLoop] run];
return 0;
}
@implementation ShutDownHandler
- (void)computerWillShutDownNotification:(NSNotification *)notification {
NSFileHandle* file = [NSFileHandle fileHandleForUpdatingAtPath: @"./output.txt"];
[file seekToEndOfFile];
NSDateFormatter* fmt = [NSDateFormatter new];
[fmt setDateFormat:@"yyyy-MM-dd …Run Code Online (Sandbox Code Playgroud) 我试图将属性关联到数组扩展:
private var AssociatedObjectHandle: String = "BlaBLabla"
extension Array {
var emptyIndex:Int {
mutating get {
if let object = objc_getAssociatedObject(self, &AssociatedObjectHandle) {
return object as! Int
}
let index = self.searchEmptyIndex()
self.emptyIndex = index
return index
}
set {
let new = (newValue as NSInteger)
objc_setAssociatedObject(self, &AssociatedObjectHandle, new, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
func searchEmptyIndex() -> Int {
if let arr = self as? [Int] {
return arr.index(of: -1)!
}
return -1
}
}
Run Code Online (Sandbox Code Playgroud)
objc_getAssociatedObject调用总是返回nil !!
任何人都知道为什么?
关于这个,我正在敲打最后一小时...
我是 SwiftUI 的新手,我正在尝试使用.transition,但由于某种原因没有发生转换。
你可以看到下面的代码:
看法
import SwiftUI
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
if self.viewModel.model.show {
Text("Showing")
.padding()
} else {
Text("Not Showing")
.padding()
.transition(.asymmetric(insertion: .scale, removal: .opacity))
}
Button {
self.viewModel.show()
} label: {
Text("Tap to change")
}
}
}
Run Code Online (Sandbox Code Playgroud)
视图模型
class ViewModel: ObservableObject {
@Published private(set) var model = Model()
func show() {
self.model.toggleShow()
}
}
Run Code Online (Sandbox Code Playgroud)
模型
struct Model {
var show: Bool = true
mutating func toggleShow() …Run Code Online (Sandbox Code Playgroud)