简体   繁体   中英

Objective-C: dispatch_source_t DISPATCH_SOURCE_TYPE_DATA_ADD never executed

I'm trying to implement 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. 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. 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. Needless to say, newly created dispatch sources have a retain count of 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. And when ARC (Automatic Reference Counting) is used, then ARC will also manage the lifespan of GCD objects for you.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM