尝试在Xcode中归档自定义对象时出错

时间:2011-12-21 01:25:18

标签: iphone xcode cocoa-touch

我正在尝试使用NSCoder将自定义对象(我的对象是一个库,就像检查书籍的地方一样)归档到iPhone的文件系统。但是,当我尝试调用NSKeyedArchiver archiveRootObject时,收到“无法识别的选择器发送到实例”错误。该库声明NSCoding协议并实现所需的方法。我很茫然。

对象接口(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'  

如果我用一个简单的数组替换我的库对象,它就可以了。

1 个答案:

答案 0 :(得分:2)

由于此行[encoder encodeObject:numCopies forkey:@"numCopies"];

,您遇到异常

numCopies不是一个对象,它是一个原语,应该使用encodeInt:forKey:方法存储。