iphone - iOS 5 : Is it possible to write a struct to a plist file?

标签 iphone ios file struct plist

我有一个由以下定义的结构:

typedef struct {
    NSString *SportName;
    NSInteger numberOfPeriods;
    CFTimeInterval periodLength;
    NSString *periodName;
    CFTimeInterval secondaryClockTime;
    NSString *LeftSecondaryCounterName;
    NSString *RightSecondaryCounterName;
    bool PossessionArrow;
} GamePreset;

是否可以将 GamePreset 类型的变量写入 plist 文件?

最佳答案

没有内置支持将任意struct写入属性列表。您必须编写一个将结构转换为属性列表的方法。

理论上,您可以在运行时通过解析 @encode(GamePreset) 的结果来完成此操作,该结果(在编译时)被描述 GamePreset< 的字符串替换:

NSLog(@"encode = %s", @encode(GamePreset));
...
2012-03-04 00:57:43.456 encodetest[43337:903] encode = {?=@qd@d@@B}

这有严重的缺点。一是您没有获得字段名称,因此除非读者知道 struct 格式以及对 struct 的任何更改,否则您的 plist 不会特别有用。 s 布局将使保存的 plist 不可读。

另一个大缺点是@encode字符串没有任何有关结构填充的信息。解析字符串时必须考虑到它。我认为您可以使用 NSGetSizeAndAlignment 来帮助解决此问题。

如果您想冒着失去理智的风险尝试此操作,请阅读 “Type Encodings” section of the Objective-C Runtime Programming Guide

我建议您硬着头皮编写一个简单的函数,该函数采用 GamePreset * 并使用结构布局的硬编码知识返回 NSDictionary *

关于iphone - iOS 5 : Is it possible to write a struct to a plist file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9552952/

相关文章:

iphone - 带有图像和标题的 UISegmentedControl

ios - OpenGL ES 2.0 叠加的顶点位置

ios - 归档失败 : FaSTLane with Ionic 3

ios - 自定义 UITableViewSectionHeader - 图像与绘图

file - 配置 nginx 静态缓存某些 URL

iphone - 是否可以将动画插入到切换 View 时显示的 UITabBarController 中?

ios - 与 iPad 失去连接

ios - 获取服务 'applinks' 的信息,应用 ID '<<NULL>>'

java使用 "../../"构建的相对路径无法识别,为什么?

file - 在 Rust 中以读写模式打开文件