[英]NSKeyedUnarchiver. Loading array of custom objects from plist
我正在嘗試加載我的.plist文件
放入我的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] ***由於未捕獲的異常'NSInvalidArgumentException'而終止應用程序,原因:'-[__ NSCFArray objectForKey:] :無法識別的選擇器發送到實例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類來幫助您。
是的,似乎我對歸檔和序列化感到很困惑。 因此,我將代碼修改如下:
-(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];
}
}
看起來不錯。 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.