修改macOS CLI代码,提取NSDistributedNotification的userInfo中path值
获取分布式通知中的Path值
嘿,我来帮你修改代码,让它只输出userInfo里的path值!其实逻辑很简单,只需要调整receive:方法里的内容就行,我一步步给你拆解:
关键修改思路
你需要从传入的NSNotification对象里拿到userInfo字典,再从中取出path对应的字符串值,最后把Objective-C的字符串转换成C语言能识别的格式输出(和你之前用fprintf的方式匹配)。
修改后的receive:方法
把原来的receive:方法替换成下面这段代码就可以了:
-(void) receive: (NSNotification*) notification { // 从通知对象中取出userInfo字典 NSDictionary *userInfo = [notification userInfo]; // 从字典里获取"path"对应的字符串值 NSString *pathString = [userInfo objectForKey:@"path"]; // 做个判空处理,避免path不存在时程序崩溃 if (pathString) { // 把NSString转换成C字符串,输出到标准错误流 fprintf(stderr,"%s\n", [pathString UTF8String]); } else { fprintf(stderr,"Path not found in notification\n"); } }
完整的修改后代码
如果需要完整的代码参考,这里是全部内容:
#import <Foundation/NSObject.h> #import <Foundation/NSNotification.h> #import <Foundation/NSString.h> #import <Foundation/NSDistributedNotificationCenter.h> #import <Foundation/NSRunLoop.h> #import <stdio.h> @interface monitorcli: NSObject {} -(id) init; -(void) receive: (NSNotification*) notification; @end @implementation monitorcli -(id) init { NSDistributedNotificationCenter * center = [NSDistributedNotificationCenter defaultCenter]; [center addObserver: self selector: @selector(receive:) name: @"TheApplicationNotification" object: nil ]; fprintf(stderr,"Listening...\n"); [[NSRunLoop currentRunLoop] run]; fprintf(stderr,"Stopping...\n"); return self; } -(void) receive: (NSNotification*) notification { NSDictionary *userInfo = [notification userInfo]; NSString *pathString = [userInfo objectForKey:@"path"]; if (pathString) { fprintf(stderr,"%s\n", [pathString UTF8String]); } else { fprintf(stderr,"Path not found in notification\n"); } } @end int main( int argc, char ** argv) { [[monitorcli alloc] init]; return 0; }
额外小提示
- 我加了
if (pathString)的判空逻辑,万一通知里的userInfo没有path这个键,程序不会崩溃,而是输出提示信息,更稳妥。 - 如果你想把输出传给shell脚本处理,可以把
stderr改成stdout(标准输出流),这样就能直接用管道或者重定向来处理路径内容了。
内容的提问来源于stack exchange,提问作者JayB
相关产品推荐
相关产品推荐

