iOS 结构体存入字典以及读取

2020-11-16  本文已影响0人  Accepted_

字典内只能存储对象,非对象数据就需要转成对象来存储。
比方说基本类型NSInteger、CGFloat等等用@()包起来就可以存储,CGPoint、CGRect可以使用NSStringFromXXX来转成字符串存储。

以下为自定义结构体存入字典的方法:

//结构体定义示例
typedef struct {
    int left;
    int top;
    int right;
    int bottom;
} X_POS;

...

//存入字典
NSMutableDictionary * tempDict = [NSMutableDictionary dictionary];
X_POS pos1;
pos1.left = 0;
pos1.top = 0;
pos1.right = 0;
pos1.bottom = 0;
NSValue * valueSE = [NSValue valueWithBytes:&pos1 objCType:@encode(X_POS)];
[tempDict setValue:valueSE forKey:@"位置"];

...

//从字典取出
VAT_POS getPos;
[tempDict[@"位置"] getValue:&getPos];
NSLog(@"%d %d %d %d", getPos.left, getPos.top, getPos.right, getPos.bottom);

上一篇 下一篇

猜你喜欢

热点阅读