zoukankan      html  css  js  c++  java
  • 结构体和NSData相互转换

    假设有这么一个结构体:

          struct   MYINFO

         {

             int   a;

             long  b;

             char  c;

         };  

        struct  MYINFO    infoStruct;

        infoStruct.a = 100;

        infoStruct.b =10000;

        infoStruct.c = 'c';

         1.   将   infoStruct转换为NSData 

         NSData * msgData = [[NSData alloc]initWithBytes:&infoStruct length:sizeof(infoStruct)];

         2.  将    msgData转换为  MYINFO  对象。

          struct  MYINFO  infoStruct2;

          [msgData getBytes:&infoStruct2 length:sizeof(infoStruct2)]; 

    多个结构体如何使用NSData包装

       

    也许你已经非常习惯了使用NSArray和NSDictionary写成.plist来保存游戏的分数记录,非常爽吧,但是对于用惯了C的人会感觉很难受,你必须的先将他们整理成整齐的ObjC格式才行,这里将介绍一种保存任意类型的方法。可能有点小题大作,但毕竟符合一部份人的使用习惯。

     

    //先来两结构,注意我们要保存的可以是 int ,float,NSString,居然还可以是UIImage

    typedef struct _INT{

    int t1;

    int t2;

    }INT_STRUCT;

    typedef struct _STRING{

    NSString *st1;

    NSString *st2;

    UIImage *image;

    }STRING_STRUCT;

     

    //初始化两个变量

    INT_STRUCT theInt = {2,5};

    STRING_STRUCT theString = {@"string1",@"string2",[UIImage imageNamed:@"icon57.png"]};

     

    //将这两个变量添加到data中,他们现在是二进制

    NSMutableData *theData = [NSMutableData data];

    [theData appendBytes:&theInt length:sizeof(INT_STRUCT)];

    [theData appendBytes:&theString length:sizeof(STRING_STRUCT)];

     

    //保存到你的路径,可以不需要后缀名

    [theData writeToFile:@"mySave" atomically:YES]; 


    //读取

    INT_STRUCT newInt;

    STRING_STRUCT newString;

    NSMutableData *newData = [NSData dataWithContentsOfFile:@"mySave"];


    //按地址赋值,注意range的范围

    [newData getBytes:&newInt range:NSMakeRange(0,sizeof(INT_STRUCT))];

    [newData getBytes:&newString range:NSMakeRange(sizeof(INT_STRUCT),sizeof(INT_STRUCT)+sizeof(STRING_STRUCT))];

    NSLog(@"newInt.t1===%d",newInt.t1);

    NSLog(@"newString.image===%@",newString.image); 

    NSLog(@"theString.image===%@",theString.image); 

    OK,比较一下我们输出的newString.image和theString.image,值是一样的,你可以用UIImageView将它显示出来,看看对不对 

  • 相关阅读:
    【新梦想Java开发公开课】
    接口自动化框架httprunner(三)--断言
    接口自动化框架httprunner(二)--变量空间(context)作用域
    接口自动化框架httprunner(一)--安装及简单使用
    python+locust性能测试(四)之分布式运行
    安装Resharper 10.0.X 出现 The CrossAppDomainPointer is NULL 错误解决方案之一
    给DNN装SkinTuner扩展时出现Could not load file or assembly 'System.Data.SQLite
    STA和MTA线程模式的区别
    jQuery插件,迅速的实现拖拽功能
    query插件(三):Colorbox–内容播放插件
  • 原文地址:https://www.cnblogs.com/chengfang/p/4093451.html
Copyright © 2011-2022 走看看