简体   繁体   English

在NSCache中存储struct的任何方法

[英]Any way to store struct in NSCache

Is there any way to store struct values in NSCache ? 有没有办法在NSCache中存储struct值? When I read the apple documentation look like you can only store AnyObject to it. 当我阅读Apple文档时,您只能将AnyObject存储到它。 There are couple of work around one is convert sturct to class, second convert sturct values to the dictionary but they are very expensive operation if dataset is big. 有一些工作是将sturct转换为class,第二个将sturct值转换为字典,但如果数据集很大则它们是非常昂贵的操作。 Any suggestion? 有什么建议吗?

I'm going to chance my arm on a 'no' (without workarounds). 我要把手臂放在'不'上(没有解决方法)。 NSCache is resoundingly over on the Objective-C side of the runtime, written to work with NSObject s, bridged via AnyObject . NSCache在运行时的Objective-C方面非常响亮,编写为与NSObject协同工作,通过AnyObject桥接。 Unlike NSDictionary and NSArray there is no equivalent Swift collection that the compiler can bridge between. NSDictionaryNSArray不同,编译器之间没有等效的Swift集合。

Implementation points aside: NSCache simply doesn't live in a world that understands value semantics for anything more sophisticated than C atoms. 除了实现要点: NSCache根本不存在于理解比C原子更复杂的价值语义的世界中。

That being said, probably the easiest workaround is just to create an object container for your struct, making the bridging explicit but owned by whomever wants to use the cache: 话虽这么说,可能最简单的解决方法就是为你的struct创建一个对象容器,使桥接显式但由任何想要使用缓存的人拥有:

class YourStructHolder: NSObject {
    let thing: YourStruct
    init(thing: YourStruct) {
        self.thing = thing
    }
}

cache.setObject(YourStructHolder(thing: thing), forKey:"Whatever")
(cache.objectForKey("Whatever") as? YourStructHolder)?.thing

... or skip the init and use a var ...: YourStruct? ...或者跳过init并使用var ...: YourStruct? if you're happy with mutability. 如果你对可变性感到满意 You're going to have to deal with optionality when talking to the cache anyway. 无论如何,在与缓存交谈时,你将不得不处理可选性。

The best option in this case is to use a template. 在这种情况下,最好的选择是使用模板。 That way, you can maintain type safety, and you don't have to force downcast. 这样,您可以保持类型安全,并且您不必强制转发。

class StructWrapper<T>: NSObject {

    let value: T

    init(_ _struct: T) {
        self.value = _struct
    }
}

I don't think converting struct to NSValue is very expensive (both are almost pure data) but you have to make some measuring: 我不认为将struct转换为NSValue非常昂贵(两者都是纯粹的数据),但你必须做一些测量:

struct myStruct {
    int x;
    int y;
};
typedef struct myStruct myStruct;

To wrap: 包装:

NSValue *object = [NSValue value:&myStruct withObjCType:@encode(myStruct)];

To unwrap: 打开包装:

myStruct struct;
[object getValue:&struct];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM