ios - NSKeyedUnarchiver。从 plist 加载自定义对象数组

标签 ios objective-c plist

我正在尝试加载我的 .plist 文件 enter image description here

进入我的自定义对象数组,称为 Property。这是Property.h:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface Property : NSObject<NSCoding> {
    int price_base;
    float state;
    float infrastructure;
}

-(id)initWithCoder:(NSCoder *)decoder;
-(void)encodeWithCoder:(NSCoder *)aCoder;
@end

Property.m:

#import "Property.h"

@implementation Property
-(void)encodeWithCoder:(NSCoder *)aCoder 
{/*No need to encode yet*/}
-(id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {

        price_base = [decoder decodeIntForKey:@"price_base"];
        state = [decoder decodeFloatForKey:@"state"];
        infrastructure = [decoder decodeFloatForKey:@"infrastructure"];
    }
    return self;
}
@end

接下来是执行尝试加载对象的代码:

-(void)loadProperty
{
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"Property" ofType:@"plist"];
    NSMutableArray *propertyArray = [[NSMutableArray alloc] init];
    propertyArray = [[NSKeyedUnarchiver unarchiveObjectWithFile:resourcePath] mutableCopy];
}

有一个异常,在运行时,删除下一​​个:

[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x7f99e5102cc0 2015-04-30 17:40:52.616 RealEstate[5838:2092569] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x7f99e5102cc0'

有没有人知道,代码可能有什么问题?我是 XCode 和 ObjectiveC 的新手,非常感谢您的帮助!

最佳答案

您混淆了归档和序列化。

NSString *resourcePath = 
    [[NSBundle mainBundle] pathForResource:@"Property" ofType:@"plist"];
NSMutableArray *propertyArray = [[NSMutableArray alloc] init];
propertyArray = 
    [[NSKeyedUnarchiver unarchiveObjectWithFile:resourcePath] mutableCopy];

这不是您阅读 .plist 文件的方式。它没有存档,你不需要解压器来阅读它。它是一个数组,因此只需将其直接读入 NSArray (initWithContentsOfFile:)。

结果,一切都将是不可变的。如果这不是您想要的,您需要 NSPropertyListSerialization 类来帮助您。

关于ios - NSKeyedUnarchiver。从 plist 加载自定义对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29970780/

相关文章:

iOS:在 UIPanGestureRecognizer 事件中获取组件 ID

ios - 如何使用 ZipKit 压缩文件夹?

objective-c - 尝试将 Swift 与 Obj C header 用于 Coda2 插件。获取错误 : Undefined symbols for architecture x86_64

objective-c - NSDictionary 只返回一项

objective-c - .plist 文件写入失败!这段代码有什么问题?

iPhone + 配置文件 + app-info.plist + entitlements.plist = iPhoneApp ?如何 ? entitlemets.plist 到底有什么作用?

iphone - 如何加载正确的本地化文件?

ios - EZAudio - 如何使用 EZAudioPlotGL 根据 View 大小更改相同的波形大小

xcode - 使用 xcode 调试 "failed to launch in time"

iphone - 保存和显示 textfield.text