我正在尝试加载我的 .plist 文件
进入我的自定义对象数组,称为 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/