• 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的封装,不过这只是个人推测而已!!

     
  • 相关阅读:
    越大优先级越高,优先级越高被OS选中的可能性就越大
    锁标记如果过多,就会出现线程等待其他线程释放锁标记
    使用带缓冲区的输入输出流的速度会大幅提高
    Bufferread有readline()使得字符输入更加方便
    java的开发主要以http为基础
    UDP也需要现有Server端,然后再有Client端
    端口是一种抽象的软件结构,与协议相关
    具有全球唯一性,相对于internet,IP为逻辑地址
    判断是否一个属性或对象可序列化
    把对象通过流序列化到某一个持久性介质称为对象的可持久化
  • 原文地址:https://www.cnblogs.com/willbin/p/2957404.html
Copyright © 2020-2023  润新知