gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:46:29 25 4
gpt4 key购买 nike

我正在尝试加载我的 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com