一种是基于文件的模式
也就是在后台程序中设定一个定时器,定时读取用户交互信息的文件,这样实现的通信机制,虽然也解决了问题,但是,缺陷是需要一直跑一个定时器来查询前台是否传递信息过来了
还有一种是使用CFMessagePortRef
典型的如下模式:
#define APP_ID "yohunl.support.mach.port"
#define MACH_PORT_NAME APP_ID
在后台进程中创建一个用于进程通讯的 CFMessagePortRef
CFMessagePortRef local = CFMessagePortCreateLocal(kCFAllocatorDefault, CFSTR(MACH_PORT_NAME), mouseCallBack, NULL, NULL);
CFRunLoopSourceRef source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, local, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
其中的mouseCallback是回调函数,其声明是
CFDataRef mouseCallBack(CFMessagePortRef local, SInt32 msgid, CFDataRef cfData, void *info);
在前台进程中使用发送消息的模式
CFMessagePortRef bRemote = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR(MACH_PORT_NAME));
// tell thread b to print his name
char message[255]="lingdaiping,yohunl";
CFDataRef data;
data = CFDataCreate(NULL, (UInt8 *)message, strlen(message)+1);
(void)CFMessagePortSendRequest(bRemote, CFSTR(MACH_PORT_NAME), data, 0.0, 0.0, NULL, NULL);
CFRelease(data);
CFRelease(bRemote);
将字典转化为二进制
NSMutableData*data =[[NSMutableData alloc]init];NSKeyedArchiver*archiver =[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];[archiver encodeObject:YOURDICTIONARY forKey: YOURDATAKEY];
archiver finishEncoding];[data writeToFile:YOURFILEPATH atomically:YES];[data release];[archiver release];
To get the NSDictionary back from the stored NSData
NSData*data =[[NSMutableData alloc]initWithContentsOfFile:YOURFILEPATH];NSKeyedUnarchiver*unarchiver =[[NSKeyedUnarchiver alloc] initForReadingWithData:data];
YOURDICTIONARY =[unarchiver decodeObjectForKey: YOURDATAKEY];[unarchiver finishDecoding];[unarchiver release];[data release];
还有一种信号量的机制,本人也还没研究,但是看见过别的程序中有使用过,应该也是可以的!!
最近又发现了一种方式:CPDistributedMessagingCenter方式,这个貌似就是上面的方法2的封装,不过这只是个人推测而已!!