如何在NSMutableDictionary中存储自定义对象? [英] how to store custom objects in NSMutableDictionary?

查看:124
本文介绍了如何在NSMutableDictionary中存储自定义对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS的新手.我有一个从 NSObject 派生的类,我想将其引用存储到 NSMutableDictionary 中.我怎样才能?例如

I'm new to iOS. I have a class derived from NSObject and I want to store its reference into NSMutableDictionary. How can I? e.g.

    @interface CustomClass : NSObject
    {
    }

我想将此CustomClass的引用(* customClass)存储到 NSMutableDictionary 中.请给我简单的方法来存储和检索它.

I want to store reference (*customClass) of this CustomClass into NSMutableDictionary. Please give me the simple way to store and retrieve it.

推荐答案

为此,您需要使用NSKeyedArchiver和NSCoder类,如下所示:

For that purpose, you need to use NSKeyedArchiver and NSCoder classes, as following:

在CustomClass.m文件中,实现以下两种编码和解码方法:

In your CustomClass.m file, implement the following two encoding and decoding methods :

- (void)encodeWithCoder:(NSCoder *)encoder {
    // encoding properties 
    [encoder encodeObject:self.property1 forKey:@"property1"];
    [encoder encodeObject:self.property2 forKey:@"property2"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        // decoding properties 
        self.property1 = [decoder decodeObjectForKey:@"property1"];
        self.property2 = [decoder decodeObjectForKey:@"property2"];
    }
    return self;
}

使用它来设置和获取这样的对象:

Use it for setting and getting object like this:

 // For setting custom class objects on dictionary

 CustomClass * object = /*..initialisation....*/;
 NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
 [dictionary setObject:encodedObject forKey:key];

 // For getting custom class objects from dictionary

 NSData *encodedObject = [dictionary objectForKey:key];
 CustomClass * object = (CustomClass *)[NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];

更新:更好的方法是使用简单易用的第三方库:RMMapper- https://github.com/roomorama/RMMapper

UPDATE: Better way is to use simple and easy to use third party library: RMMapper - https://github.com/roomorama/RMMapper

这篇关于如何在NSMutableDictionary中存储自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆