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

NSKeyedUnarchiver. Loading array of custom objects from plist

我正在尝试加载我的 .plist 文件

进入我的自定义对象数组,称为 属性。这里是 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 class 来帮助你。

是的,我似乎对归档和序列化感到很困惑。所以,我修改了代码如下:

-(void)loadProperty
{
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"Property" ofType:@"plist"];
    NSArray *temp = [[NSArray alloc] initWithContentsOfFile:resourcePath];
    NSMutableArray *propertyArray = [[NSMutableArray alloc] init];
    for(NSDictionary *dict in temp) {
        Property *prop = [Property alloc];
        prop.price_base = (int)[[dict valueForKey:@"price_base"] integerValue];
        prop.state = [[dict valueForKey:@"state"] floatValue];
        prop.infrastructure = [[dict valueForKey:@"infrastructure"] floatValue];

        [propertyArray addObject:prop];
    }
}

而且看起来效果不错。谢谢!