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

时间:2015-04-30 14:44:06

标签: ios objective-c plist

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

进入我的cusom对象数组,称为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:]:发送到实例的无法识别的选择器   0x7f99e5102cc0 2015-04-30 17:40:52.616 RealEstate [5838:2092569] ***   由于未捕获的异常而终止应用程序   &#39; NSInvalidArgumentException&#39;,原因:&#39; - [__ NSCFArray objectForKey:]:   无法识别的选择器发送到实例0x7f99e5102cc0&#39;

有没有人有任何想法,代码可能有什么问题?我对XCode和ObjectiveC很新,所以帮助会非常感激!

1 个答案:

答案 0 :(得分:0)

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

-(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];
    }
}

似乎工作正常。谢谢!