[英]Objective-C: dispatch_source_t DISPATCH_SOURCE_TYPE_DATA_ADD never executed
I'm trying to implement dispatch_source_t
. 我正在尝试实现
dispatch_source_t
。 Here is my implementation: 这是我的实现:
-(void)doingSomething:(NSString*)someValue
{
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler(source, ^{
NSLog(@"here %@", someValue);
NSLog(@"监听函数:%lu",dispatch_source_get_data(source));
});
dispatch_resume(source);
dispatch_source_merge_data(source, 1);
}
But this part of my implementation is never executed: 但是我的实现的这一部分从未执行:
dispatch_source_set_event_handler(source, ^{
NSLog(@"here %@", someValue);
NSLog(@"监听函数:%lu",dispatch_source_get_data(source));
});
Any of you knows why why that part of my code is never executed? 你们谁知道为什么我的那部分代码从未执行过?
I'll really appreciate your help. 非常感谢您的帮助。
You don't keep the dispatch source alive. 您不能使调度源保持活动状态。
Dispatch sources are actually no objects, they are opaque C data structures. 调度源实际上不是对象,它们是不透明的C数据结构。 When you create a dispatch source, you must call
dispatch_release(...)
on it once you are done with it to have the system release the memory associated with it. 创建调度源时,一旦完成调度,必须在其上调用
dispatch_release(...)
,以使系统释放与其关联的内存。 Nevertheless dispatch sources are reference counted, so you can also call dispatch_retain(...)
on them to increase their reference count and dispatch_release(...)
to decrease it again and once it reaches 0, the object is destroyed. 不过,调度源是按引用计数的,因此您也可以在它们上调用
dispatch_retain(...)
来增加其引用计数,并dispatch_release(...)
来再次减小其引用计数,一旦它达到0,该对象就被销毁。 Needless to say, newly created dispatch sources have a retain count of 1. 不用说,新创建的调度源的保留计数为1。
However, when using dispatch sources in Objective-C code, you can make the Obj-C runtime pretend that GCB objects are in fact Obj-C objects by setting the compiler flag OS_OBJECT_USE_OBJC
which is enabled by default. 但是,在Objective-C代码中使用调度源时,可以通过设置默认情况下启用的编译器标志
OS_OBJECT_USE_OBJC
来使Obj-C运行时假装GCB对象实际上是Obj-C对象。 And when ARC (Automatic Reference Counting) is used, then ARC will also manage the lifespan of GCD objects for you. 并且当使用ARC(自动参考计数)时,ARC还将为您管理GCD对象的寿命。
Assuming that both applies to your code, GCD objects are treated as Obj-C objects and ARC is enabled, your dispatch source is destroyed as soon as the method -doingSomething:
finishes as this method had the only reference to the source and this reference just went out of scope. 假定这两个都适用于您的代码,将GCD对象视为Obj-C对象并启用了ARC,则在方法
-doingSomething:
完成后,您的调度源将被销毁,因为该方法仅具有对源的引用,而该引用仅超出范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.