繁体   English   中英

编码和解码自定义对象

[英]Encoding and decoding custom objects

我无法编码并将包含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];
}

在此输入图像描述在此输入图像描述

这是我用来从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

在此输入图像描述

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

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

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

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

谁能帮我这个?

更新:

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

MKMapItem不符合NSCodingSSecureCoding

您需要对各个项进行编码, MKMapItem在解码时重新创建MKMapItem

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM