您好,登錄后才能下訂單哦!
NSCoding和NSSecureCoding都是Objective-C中用于對(duì)象序列化和反序列化的協(xié)議,可以通過實(shí)現(xiàn)這兩個(gè)協(xié)議來對(duì)對(duì)象進(jìn)行序列化。
要實(shí)現(xiàn)NSCoding協(xié)議,首先需要在對(duì)象中實(shí)現(xiàn)兩個(gè)方法:- (void)encodeWithCoder:(NSCoder *)aCoder和- (instancetype)initWithCoder:(NSCoder *)aDecoder。在encodeWithCoder方法中,將對(duì)象的屬性編碼到aCoder中;在initWithCoder方法中,從aDecoder中解碼出屬性值。
示例代碼如下:
@interface Person : NSObject <NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation Person
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
@end
要實(shí)現(xiàn)NSSecureCoding協(xié)議,需要在對(duì)象中實(shí)現(xiàn)一個(gè)類方法+ (BOOL)supportsSecureCoding,在這個(gè)方法中返回YES表示該對(duì)象支持安全編碼。
示例代碼如下:
@interface Person : NSObject <NSSecureCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation Person
+ (BOOL)supportsSecureCoding {
return YES;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
@end
通過實(shí)現(xiàn)NSCoding和NSSecureCoding協(xié)議,可以將對(duì)象序列化為NSData,然后可以將NSData保存到文件或者傳輸給其他系統(tǒng)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。