本文介绍了如何序列化NSDictionary / NSArray /属性列表(plist)包含NSNull的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 NSNull NSMutableDictionary 中存储一些空值,然后使用属性列表。问题是 NSNull 是不允许的,我得到属性列表是无效的格式的错误。有这个解决方法吗?看起来很奇怪,他们没有把 NSNull 放在有效的plist对象列表中。

I want to store in a NSMutableDictionary some null values using NSNull and then serialize this data using a property list. Problem is NSNull is not allowed and I get "Property list is in invalid format" error. Is there a workaround for this? Seems very surprising they didn't put NSNull on the list of valid plist objects.

推荐答案

在序列化之前,将NSArray或NSDictionary转换为NSData。以下是nsarray上用于序列化和反序列化的类别。这个舒适的处理一些数据是nsnull

I convert NSArray or NSDictionary to NSData before serializing. Following is a category on nsarray for serializing and deserializing. This comfortableby handles some data being nsnull

@implementation NSArray(Plist)

-(BOOL)writeToPlistFile:(NSString*)filename{
    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:self];
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * path = [documentsDirectory stringByAppendingPathComponent:filename];
    BOOL didWriteSuccessfull = [data writeToFile:path atomically:YES];
    return didWriteSuccessfull;
}

+(NSArray*)readFromPlistFile:(NSString*)filename{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * path = [documentsDirectory stringByAppendingPathComponent:filename];
    NSData * data = [NSData dataWithContentsOfFile:path];
    return  [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

这篇关于如何序列化NSDictionary / NSArray /属性列表(plist)包含NSNull的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 09:55