• 结构体如何使用NSData包装


    以下文字转载自:http://blog.csdn.net/iBright/article/details/5656164  向原作者表示感谢和敬意。

       

    也许你已经非常习惯了使用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);

     

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

  • 相关阅读:
    elasticsearch的基本用法
    JavaScript实现拖拽预览,AJAX小文件上传
    php四排序-选择排序
    php四排序-冒泡排序
    centos6.5编译安装lamp开发环境
    centos7.2 yum安装lamp环境
    chrome升级54以后,显示Adobe Flash Player 因过期而遭到阻止
    chrome45以后的版本安装lodop后,仍提示未安装解决
    APACHE重写去除入口文件index.php
    PHP之factory
  • 原文地址:https://www.cnblogs.com/li-baibo/p/3185638.html
Copyright © 2020-2023  润新知