2013-11-序列化与编码,地图计算距离

本文详细介绍了如何使用编码与序列化技术将自定义的类存储到NSUserDefault中,包括实现NSCoding协议的两个关键方法,并提供了从NSUserDefault中获取自定义类的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.序列化与编码

编码与序列化:
有需要要保存自定义的class,NSUserDefault不能存储,只能通过编码与序列化的方式后存储到userdefault。
编码:class—>nsdata,序列化:nsdata->clas.自定义的类必须实现NSCoding协议。实现该协议的两个方法,如下:

@interface labelContentList : NSObject<NSCoding> //酒店标签列表
@property (nonatomic,retain) NSString *labelName;
@property (nonatomic,retain) NSString *labelType; 
@property (nonatomic,retain) NSString *labelId;
@end

@implementation labelContentList
@synthesize labelId;
@synthesize labelName;
@synthesize labelType;

//序列化与编码,为存储到本地用
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.labelId forKey:@"labelId"];
    [aCoder encodeObject:self.labelName forKey:@"labelName"];
    [aCoder encodeObject:self.labelType forKey:@"labelType"];
}
- (id)initWithCoder:(NSCoder *)coder {
    self = [super init];
    if (self) {
        self.labelId      = [coder decodeObjectForKey:@"labelId"];
        self.labelName    = [coder decodeObjectForKey:@"labelName"];
        self.labelType    = [coder decodeObjectForKey:@"labelType"];
    }
    return self;
}
@end



即实现 encodeWithCoder 和 initWithCoder 方法。
然后用存储:

NSData *chooseLabelContent =[NSKeyedArchiver archivedDataWithRootObject:keyWord.chooseLabelContent];
[[NSUserDefaults standardUserDefaults] setObject:chooseLabelContent forKey:@"key"];


用如下方法获取到该类:

NSData *dataChooseLabelContent=[[NSUserDefaults standardUserDefaults] objectForKey:@“key”];
labelContentList *chooseLabelContent  =[NSKeyedUnarchiver unarchiveObjectWithData:dataChooseLabelContent];

2.计算地图两点之间距离

CLLocation *location1 = [[[CLLocation alloc] initWithLatitude:lat1 longitude:lon1] autorelease];
CLLocation *location2 = [[[CLLocation alloc] initWithLatitude:lat2 longitude:lon2] autorelease];
CLLocationDistance distance = [location1 getDistanceFrom:location2];



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值