将 NSStrings 的 NSMutableArray 保存到磁盘

Save NSMutableArray of NSStrings to disk

我有一个 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 从网络服务器获取文本数据,然后我将这个对象添加到 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 class 需要实现 encodeWithCoder: - 如异常消息所述,Event class 未实现此方法。

此外,您应该使用小写的 s 表示单例,因为它是一个实例,而不是 class,并且您可能不应该使用单例。