Iphone 尝试在Xcode中存档自定义对象时出错
我正试图使用Iphone 尝试在Xcode中存档自定义对象时出错,iphone,xcode,cocoa-touch,Iphone,Xcode,Cocoa Touch,我正试图使用NSCoder将一个自定义对象(我的对象是一个图书馆,就像在借书的地方一样)归档到iPhone的文件系统中。但是,当我尝试调用NSKeyedArchiver archiveRootObject时,我收到一个错误“无法识别的选择器发送到实例”。库声明NSCoding协议并实现所需的方法。我不知所措 对象接口(library.h): 最后是viewController(libTableViewController.m) 以下是错误: 2011-12-18 12:13:38.799 Lib
NSCoder
将一个自定义对象(我的对象是一个图书馆,就像在借书的地方一样)归档到iPhone的文件系统中。但是,当我尝试调用NSKeyedArchiver archiveRootObject
时,我收到一个错误“无法识别的选择器发送到实例”。库声明NSCoding
协议并实现所需的方法。我不知所措
对象接口(library.h):
最后是viewController(libTableViewController.m)
以下是错误:
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-encodeObject:numCopies-forkey:@“numCopies”]代码>
numCopies
不是对象,它是原语,应该使用encodeInt:forKey:
方法存储 不幸的是,这并没有解决问题。我将行更改为:[编码器encodeInt:numCopies-forkey:@“numCopies”];但我在那行代码中得到了同样的异常。
#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"];
}
//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'