Objective-C基礎(chǔ) 自定義對象歸檔詳解及簡單實例
更新時間:2017年04月08日 10:24:30 投稿:lqh
這篇文章主要介紹了Objective-C基礎(chǔ) 自定義對象歸檔詳解及簡單實例的相關(guān)資料,需要的朋友可以參考下
自定義對象要實現(xiàn)歸檔必須實現(xiàn)NSCoding協(xié)議
NSCoding協(xié)議有兩個方法,encodeWithCoder方法對對象的屬性數(shù)據(jù)做編碼處理,initWithCoder解碼歸檔數(shù)據(jù)來初始化對象。
示例1
.h頭文件
#import <Foundation/Foundation.h> @interface user : NSObject <NSCoding> @property(nonatomic,retain)NSString *name; @property(nonatomic,retain)NSString *email; @property(nonatomic,retain)NSString *pwd; @property(nonatomic,assign)int age; @end
.m實現(xiàn)文件
#import "user.h"
#define AGE @"age"
#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"
@implementation user
//對屬性編碼
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeInt:_age forKey:@"age"];
[aCoder encodeObject:_name forKey:AGE];
[aCoder encodeObject:_email forKey:EMAIL];
[aCoder encodeObject:_pwd forKey:PASSWORD];
}
//對屬性解碼
- (id)initWithCoder:(NSCoder *)aDecoder
{
self=[super init];
if(self)
{
self.age=[aDecoderdecodeIntForKey:AGE];
self.name=[aDecoderdecodeObjectForKey:NAME];
self.email=[aDecoderdecodeObjectForKey:EMAIL];
self.pwd=[aDecoderdecodeObjectForKey:PASSWORD];
}
return self;
}
-(void)dealloc
{
[_name release];
[_email release];
[_pwd release];
[super dealloc];
}
@end
main函數(shù)的調(diào)用
user *userObj=[[user alloc] init];
userObj.age=33;
userObj.email=@"adfdadf@qq.com";
userObj.pwd=@"212212";
userObj.name=@"ricard";
NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/custom.text"];
BOOL succ=[NSKeyedArchiver archiveRootObject:userObj toFile:path];
if (succ) {
NSLog(@"Hello, World!");
user *usertemp=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
詳解iOS App設(shè)計模式開發(fā)中對于享元模式的運用
這篇文章主要介紹了iOS App設(shè)計模式開發(fā)中對于享元模式的運用,示例代碼為傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-04-04
IOS 開發(fā)之應(yīng)用喚起實現(xiàn)原理詳解
這篇文章主要介紹了IOS 開發(fā)之應(yīng)用喚起實現(xiàn)原理詳解的相關(guān)資料,需要的朋友可以參考下2016-12-12
ios開發(fā):一個音樂播放器的設(shè)計與實現(xiàn)案例
本篇文章主要介紹了ios開發(fā):一個音樂播放器的設(shè)計與實現(xiàn)案例,具有一定的參考價值,有需要的小伙伴可以參考下。2016-11-11

