0
我試圖使用NSCoder
將自定義對象(我的對象是一個庫,如在檢查出圖書的地方)存檔到iPhone的文件系統。但是,當我嘗試撥打NSKeyedArchiver archiveRootObject
時,出現「發送到實例的無法識別的選擇器」錯誤。該庫聲明NSCoding
協議並實現所需的方法。我很茫然。嘗試在Xcode中存檔自定義對象時出錯
對象接口(library.h):
#import <Foundation/Foundation.h>
@interface Library : NSObject <NSCoding> {
int numCopies;
NSString *location;
NSString *locationInfo;
NSString *material;
NSString *library;
}
+ (id)library;
@property (nonatomic) int numCopies;
@property (retain) NSString *location;
@property (retain) NSString *locationInfo;
@property (retain) NSString *material;
@property (retain) NSString *library;
- (void)encodeWithCoder:(NSCoder *)encoder;
- (void)initWithCoder:(NSCoder *)decoder;
@end
對象實現的相關部分(library.m):
#import "library.h"
@implementation Library
@synthesize numCopies;
@synthesize location;
@synthesize locationInfo;
@synthesize material;
@synthesize library;
+ (id)library
{
return [[Library alloc] init];
}
-(void)encodeWithCoder:(NSCoder *)encoder
{
//for each instance variable, archive it under its variable name
[encoder encodeObject:numCopies forkey:@"numCopies"];
[encoder encodeObject:location forkey:@"location"];
[encoder encodeObject:locationInfo forkey:@"locationInfo"];
[encoder encodeObject:material forkey:@"material"];
[encoder encodeObject:library forkey:@"library"];
}
最後,的viewController(libTableViewController.m)
//try to archive the library object
NSString *savePath = pathInDocumentDirectory(@"lib.data");
NSLog(@"try to archive library to path: %@", savePath);
[NSKeyedArchiver archiveRootObject:this_lib toFile:savePath];
這是錯誤:
2011-12-18 12:13:38.799 LibraryFiend2[12877:207] try to archive library to path: /Users/kclary/Library/Application Support/iPhone Simulator/4.3/Applications/71B11434-3307-449A-9E95-5E22034E7FA0/Documents/lib.data
2011-12-18 12:13:38.800 LibraryFiend2[12877:207] -[NSKeyedArchiver encodeObject:forkey:]: unrecognized selector sent to instance 0x4b1a130
2011-12-18 12:13:38.801 LibraryFiend2[12877:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSKeyedArchiver encodeObject:forkey:]: unrecognized selector sent to instance 0x4b1a130'
terminate called after throwing an instance of 'NSException'
如果我將一個簡單的數組替換爲我的庫對象,它就可以工作。
不幸的是,這並沒有解決問題。我將該行更改爲:[encoder encodeInt:numCopies forkey:@「numCopies」];但是我在這行代碼中遇到了同樣的異常。 –