gpt4 book ai didi

ios - 将 NSStrings 的 NSMutableArray 保存到磁盘

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

我有一个 NSString 对象的 NSMutableaArray。所以我正在使用 NSKeyedArchiever 将它保存到磁盘。所以当我尝试使用

- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.EventsList forKey:@"Events"];
}

我遇到了一个错误

   Event encodeWithCoder:]: unrecognized selector sent to instance 0x7fd06b542780

这是我的部分代码:

//-------------------Events.h--------------------------

@interface Event : NSObject
@property (strong,nonatomic) NSString *nameOfEvent;
@property (strong,nonatomic) NSString *dateOfEvent;
@property (strong,nonatomic) NSString *placeOfEvent;
@property int priorityOfEvent;
@end

//---------------Singleton.h ----------------
@interface GlobalSingleton : NSObject <NSCoding, NSCopying> {
NSMutableArray *EventsList;
}
@property (nonatomic,retain) NSMutableArray *EventsList;
+(GlobalSingleton *)sharedFavoritesSingleton;
@end

//----------------Singleton.m------------------------
....

@implementation GlobalSingleton
@synthesize EventsList;

....
....

- (void)encodeWithCoder:(NSCoder *)aCoder {
NSLog (@"%@",EventsList); // not nil
[aCoder encodeObject:self.EventsList forKey:@"Events"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super init])) {
NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:[aDecoder decodeObjectForKey:@"Events"]];
self.EventsList = temp;
}
return self;
}

- (id)copyWithZone:(NSZone *)zone {
GlobalSingleton *copy = [[GlobalSingleton allocWithZone:zone] init];
copy.EventsList = self.EventsList;
return copy;
}
@end

我使用 JSON 格式的 ASIFormDataRequest 从 Web 服务器获取文本数据,然后我将这个对象添加到 NSMutableArray,它也是一个单例,所以它看起来像这样:

    NSDictionary *responseDict = [responseString JSONValue];
GlobalSingleton *Singleton = [GlobalSingleton sharedFavoritesSingleton];
for (NSDictionary *str in responseDict) {
Event *newEvent = [[Event alloc] init];
newEvent.nameOfEvent = [str objectForKey:@"EventName"];
newEvent.dateOfEvent = [str objectForKey:@"EventDate"];
newEvent.placeOfEvent = [str objectForKey:@"EventPlace"];
[Singleton.EventsList addObject:newEvent];

}
//------------------Save this data stored in NSMutableArray to disk-------------------------
[NSKeyedArchiver archiveRootObject:Singleton toFile:[self save_path]];

因此,再次执行停止:

  [aCoder encodeObject:self.EventsList forKey:@"Events"];

但是当我尝试编写单个 NSString 对象时,一切都没有错误。

最佳答案

eventList 不包含 NSStrings,它包含 Event 对象。

您的 Event 类需要实现 encodeWithCoder: - 如异常消息所述,Event 类未实现此方法。

此外,您应该对单例使用小写的 s,因为它是一个实例,而不是一个类,您可能不应该使用单例。

关于ios - 将 NSStrings 的 NSMutableArray 保存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29340789/

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