将NSObject转换为NSDictionary

时间:2016-05-18 07:27:55

标签: ios objective-c iphone ipad nsdictionary

如何将NSObject转换为NSDictionary?

在第一步,我已将NSDictionary转换为NSObject,如

QRCodeData *obj = [[QRCodeData alloc] initWithQRcodeData:myDictonary];

QRCodeData.h

@interface QRCodeData : NSObject
-(instancetype)initWithQRcodeData:(NSDictionary*)dictionary;
@end

QRCodeData.m

@implementation QRCodeData

-(instancetype)initWithQRcodeData:(NSDictionary*)dictionary
{
    self = [super init];
    if(self){

        self.name = dictionary[@"userName"];
        self.phoneNumber = dictionary[@"mobileNo"];

    }
    return self;

}
@end

我想从对象中获取我的词典,有可能得到吗?

请提前帮助并表示感谢..

3 个答案:

答案 0 :(得分:3)

最简单的方法是在QRCodeData类中添加此方法。

- (NSDictionary *)dictionaryValue
{
  return @{@"userName" : self.name, @"mobileNo" : self.phoneNumber};
}

如果userNamephoneNumber可能是nil,您必须检查一下。

使用

进行通话
NSDictionary *dict = [obj dictionaryValue];

答案 1 :(得分:3)

你可以简单地获得字典,

onPause()

此处 NSDictionary *dict = @{@"userName": obj.name ,@"mobileNo" : obj.phoneNumber }; obj的对象。

希望这会有所帮助:)

答案 2 :(得分:2)

您可以使用键值编码(KVC)来实现此目的。首先,为要共享的所有键提供类方法:

+ (NSSet *)keysToCopy
{
    return [NSSet setWithObjects:@"userName", @"mobileNio", .....];
}

然后你可以在你的init方法中做一些事情:

for (key in [[self class] keysToCopy])
{
    [self setValue:dictionary[key] forKey:key];
}

并提供另一种方法将其还原为NSDictionary

- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    for (key in [[self class] keysToCopy])
    {
        [result setObject:[self valueForKey:key] forKey:key];
    }
}

唯一的问题仍然是并非每个属性都与NSDictionary存储兼容。

这种方法允许您将此解决方案扩展到任何Cocoa对象,并且除了keysToCopy方法之外,如果有新属性要共享,则不需要您更改任何内容。