Objective c 如何在plist中存储对象

Objective c 如何在plist中存储对象,objective-c,encryption,nsdictionary,plist,nsvalue,Objective C,Encryption,Nsdictionary,Plist,Nsvalue,我有一些CGPoints需要存储在NSDictionary中,然后写入文件。稍后,我需要能够将文件加载到NSDictionary中并访问其中的CGPoint self.dict是我要存储点的NSDictionary - (void)setPoint:(CGPoint)point forKey:(NSString *)key { NSValue *value = [NSValue valueWithCGPoint:point]; [self.dict setValue:value

我有一些CGPoints需要存储在NSDictionary中,然后写入文件。稍后,我需要能够将文件加载到NSDictionary中并访问其中的CGPoint

self.dict是我要存储点的NSDictionary

- (void)setPoint:(CGPoint)point forKey:(NSString *)key {
    NSValue *value = [NSValue valueWithCGPoint:point];
    [self.dict setValue:value forKey:key];
}
我还想对信息进行加密。因此,我将NSDictionary转换为NSData以对其进行加密

- (void)encryptDictionaryWithKey:(NSData *)key writeToFile:(NSString *)file {
    NSData *encryptedDict = [[NSKeyedArchiver archivedDataWithRootObject:self] encryptWithKey:key];
    [encryptedDict writeToFile:file atomically:YES];
}
然后,要从文件中获取信息,请对其进行解密,并将其转换为NSDictionary格式:

我可以将其他一些值(如NSNumber)放入NSDictionary,加密并写入文件,然后从文件中获取并解密。。。而价值观仍然是得体的。所以我的代码看起来不错。但它不适用于NSValue

我用它从NSValue中获取CGPoint。此时,self.plist可能已经加密,但不一定要加密,写入文件,然后设置为文件的未加密版本

- (CGPoint)pointForKey:(NSString *)key {
    NSValue *value = [self.prefs objectForKey:key];
    return [value CGPointValue];
}
如果self.plist已加密、写入文件,然后从文件加载并未加密,则此代码仅返回0,0和value==nil

因此,在写入文件的过程中,带有CGPoint的NSValue似乎被设置为nil。我不知道我做错了什么,所以非常感谢你的帮助。谢谢

您可以将CGPoint转换为可存储在plist中的对象。例如,将CGPoint转换为NSDictionary,或者更确切地说,转换为可以转换为NSDictionary的CFDictionaryRef。您可以将其存储在plist中,然后在加载plist时使用CGPointMakeWithDictionaryRepresentation伴随函数将其转换回CGPoint

- (CGPoint)pointForKey:(NSString *)key {
    NSValue *value = [self.prefs objectForKey:key];
    return [value CGPointValue];
}