zoukankan      html  css  js  c++  java
  • iphone守护进程和前台进程之间的通信前台应用发信息给后台的守护进程

    http://blog.csdn.net/diyagoanyhacker/article/details/7872253
     
     
    当我们创建基于mobilesubstrate的应用时,通常都是一些前后台程序,典型的比如苹果皮等,这个需要前台程序法信息到后台进程中,这里有两种方式

    一种是基于文件的模式

    也就是在后台程序中设定一个定时器,定时读取用户交互信息的文件,这样实现的通信机制,虽然也解决了问题,但是,缺陷是需要一直跑一个定时器来查询前台是否传递信息过来了

    还有一种是使用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的封装,不过这只是个人推测而已!!

     
  • 相关阅读:
    606. Construct String from Binary Tree
    696. Count Binary Substrings
    POJ 3255 Roadblocks (次短路)
    POJ 2823 Sliding Window (单调队列)
    POJ 1704 Georgia and Bob (博弈)
    UVa 1663 Purifying Machine (二分匹配)
    UVa 10801 Lift Hopping (Dijkstra)
    POJ 3281 Dining (网络流之最大流)
    UVa 11100 The Trip, 2007 (题意+贪心)
    UVaLive 4254 Processor (二分+优先队列)
  • 原文地址:https://www.cnblogs.com/willbin/p/2957404.html
Copyright © 2011-2022 走看看