[英]Is it safe to create `NSEvent object` then `CGEventPost` the `[ev CGEvent]` then exit the method?
I have the following Objective-C snippet: 我有以下Objective-C片段:
void toggle()
{
NSEvent* down_event = [NSEvent keyEventWithType: NSEventTypeKeyDown
location: NSZeroPoint
modifierFlags: 0
timestamp: 0.0
windowNumber: 0
context: nil
characters: @" "
charactersIgnoringModifiers: @" "
isARepeat: false
keyCode: kVK_Space ];
CGEventPost(kCGHIDEventTap, [down_event CGEvent]);
}
The project is ARC enabled. 该项目已启用ARC。
Is this safe, or am I running the gauntlet of an occasional memory access error? 这安全吗,还是我运行了偶发的内存访问错误的手套?
I'm worried that the NSObject
may be garbage collected while the system is still making use of its CGEvent
. 我担心
NSObject
可能在系统仍在使用其CGEvent
情况下被垃圾回收。
Yes it is safe. 是的,这很安全。 The documentation for the
CGEvent
property states: CGEvent
属性的文档指出:
The
CGEventRef
opaque type returned is autoreleased.返回的
CGEventRef
不透明类型将自动释放。 If noCGEventRef
object corresponding to theNSEvent
object can be created, this method returnsNULL
.如果无法
CGEventRef
与CGEventRef
对象相对应的NSEvent
对象,则此方法返回NULL
。
This tells you that a new CGEvent
is created that corresponds to the NSEvent
. 这告诉你一个新的
CGEvent
创建 对应于NSEvent
。 If there was a dangerous dependency, eg the return value contained an unsafe reference to the original object that would be noted (there was/are methods that did/do that and were/are so documented [yes, I haven't checked if any still exist]) . 如果存在危险的依赖关系,例如返回值包含对原始对象的不安全引用,将会被注意(有/有这样做的方法,并且已经记录在案[是的,我没有检查是否有任何方法仍然存在]) 。
BTW: if you grew up in the ARC age and do not know about "autoreleased" do not concern yourself, ARC knows and will do the right thing. 顺便说一句:如果您在ARC时代长大并且不了解“自动发布”,请不要担心自己,ARC知道并且会做正确的事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.