编码和解码自定义对象

时间:2015-01-18 12:05:55

标签: ios objective-c singleton nsobject nskeyedarchiver

我无法编码并将包含MKMapItem的自定义对象列表保存到NSUserDefaults。

首先,我从用于tableView的MKMapItem数组中获取选定的MKMapItem,并将其存储在我的sharedManager实例中。 (以后将使用sharedManager中的所有值来创建自定义对象。)

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

// Get the tapped MKMapItem
MKMapItem *selectedMapItem = self.searchResults[indexPath.row];

// Create a sharedManager instance
MyManager *sharedManager = [MyManager sharedManager];

// Set the workRegion and workLocation in sharedManager
NSLog(@"selectedMapItem: %@", [selectedMapItem name]);
sharedManager.workLocation = selectedMapItem;

// Post a notification to alert the PreviewMapViewController
[[NSNotificationCenter defaultCenter] postNotificationName:@"showAnnotations" object:self.searchResults];
[[NSNotificationCenter defaultCenter] postNotificationName:@"zoomToAnnotation" object:selectedMapItem];
[[NSNotificationCenter defaultCenter] postNotificationName:@"showMap" object:nil];
}

enter image description here enter image description here

这是我用来从sharedManager获取MKMapItem并将其放入我创建的自定义对象中的代码:

MyManager *sharedManager = [MyManager sharedManager];
newModel.workLocation = sharedManager.workLocation;

我的自定义对象将workLocation存储在其头文件中,其属性如下:

@property (nonatomic, strong) MKMapItem *workLocation;

这是我编码和解码workLocation对象的实现文件:

@implementation WorkLocationModel

-(id)init {
// Init self
self = [super init];
if (self)
{
    // Setup
}
return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.workLocation forKey:@"workLocation"];
}

-(instancetype)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self)
self.workLocation = [coder decodeObjectForKey:@"workLocation"];
return self;
}

@end

enter image description here

我的断点设置为捕获encodeObject行上的所有异常中断。

将此自定义对象添加到NSMutableArray然后使用以下命令保存该数组时会发生错误:

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:_myObjects] forKey:@"myObjects"];

异常: - [MKMapItem encodeWithCoder:]:无法识别的选择器发送到实例0x7f9f14acf400

任何人都可以帮我吗?

更新

NSData *workLocationData = [NSKeyedArchiver archivedDataWithRootObject:sharedManager.workLocation];

1 个答案:

答案 0 :(得分:1)

MKMapItem不符合NSCodingSSecureCoding

您需要对单个项目进行编码,然后在解码时重新创建MKMapItem