Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c - Access app delegate function in FSEvent callback

I have created this function in app delegate file. I want to call a function of app delegate in callback.

Is there any way please suggest.

-(void) monitor{
    FSEventStreamRef stream = FSEventStreamCreate(NULL, 
                                                  &feCallback,
                                                  &cntxt, 
                                                  pathsToWatch, 
                                                  kFSEventStreamEventIdSinceNow, 
                                                  1,
                                                  kFSEventStreamCreateFlagWatchRoot );
} 

static void feCallback(ConstFSEventStreamRef streamRef,
                       void* pClientCallBackInfo,
                       size_t numEvents,
                       void* pEventPaths,
                       const FSEventStreamEventFlags eventFlags[],
                       const FSEventStreamEventId eventIds[]) 
{
    NSLog(@"The file changed!"); 
    // need to to call app delegate function
}
question from:https://stackoverflow.com/questions/65951761/access-app-delegate-function-in-fsevent-callback

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As FSEventStreamCreate is only available on macOS, you may do it the following way:

    // call this in init of your app delegate
    FSEventStreamContext  cntxt = {0, (__bridge void *)(self), NULL, NULL, NULL};
    // call FSEventStreamCreate as in your code
    // keep a reference to the stream so you can stop and start it later

Then in your callback the AppDelegate will be in:

    YourAppDelegateClass* appDele = (__bridge YourAppDelegateClass*)pClientCallBackInfo; 

The whole mechanism for FSEvents is quite complex, we had to schedule it on the right run loop and work with ARC and type casting. The callback is outside of ObjectiveC, you won't be able to use Cocoa but only CFString and other Core Foundation types. It's also helpful to not only read the documentation but look at the FSEvents.h within the Framework (context menu on any of the functions and then Jump to definition: There is more to read than in the documentation). And depending on your distribution, also work with the App Store Sandbox and security scoped bookmarks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...