ios序列化最终方案
最近在整合一些与服务器交互的东西,准备使用序列化的一些东西
使用NSCoding 来进行NSObject 的序列化实现: 整合了网上搜集的两片文章完成了功能:
http://www.cnblogs.com/likwo/archive/2011/05/26/2058134.html
- (void)encodeWithCoder:(NSCoder*)coder{
Class clazz = [self class];
u_int count;
objc_property_t* properties = class_copyPropertyList(clazz, &count);
NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++)
{
const char* propertyName = property_getName(properties[i]);
[propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
}
free(properties);
for (NSString *name in propertyArray)
{
id value = [self valueForKey:name];
[coder encodeObject:value forKey:name];
}
}
- (id)initWithCoder:(NSCoder*)decoder
{
if (self = [super init])
{
if (decoder == nil)
{
return self;
}
Class clazz = [self class];
u_int count;
objc_property_t* properties = class_copyPropertyList(clazz, &count);
NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++)
{
const char* propertyName = property_getName(properties[i]);
[propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
}
free(properties);
for (NSString *name in propertyArray)
{
id value = [decoder decodeObjectForKey:name];
[self setValue:value forKey:name];
}
}
return self;
}
http://www.cnblogs.com/Kiros/archive/2012/03/09/2387532.html
先是自定义一个自己的类 需要继承 NSCoding 接口
-------------------------------------//我是分隔线//-----------------------------------------
#import <Foundation/Foundation.h>
@interface FourLines : NSObject <NSCoding,NSCopying> {
}
@property (nonatomic,retain) NSString *field1;
@property (nonatomic,retain) NSString *field2;
@property (nonatomic,retain) NSString *field3;
@property (nonatomic,retain) NSString *field4;
@end
#import "FourLines.h"
#define kField1Key @"Field1"
#define kField2Key @"Field2"
#define kField3Key @"Field3"
#define kField4Key @"Field4"
@implementation FourLines
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
- (void) encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:field1 forKey:kField1Key];
[aCoder encodeObject:field2 forKey:kField2Key];
[aCoder encodeObject:field3 forKey:kField3Key];
[aCoder encodeObject:field4 forKey:kField4Key];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
field1 = [[aDecoder decodeObjectForKey:kField1Key] retain];
field2 = [[aDecoder decodeObjectForKey:kField2Key] retain];
field3 = [[aDecoder decodeObjectForKey:kField3Key] retain];
field4 = [[aDecoder decodeObjectForKey:kField4Key] retain];
}
return self;
}
- (id)copyWithZone:(NSZone *)zone{
FourLines *copy = [[[self class] allocWithZone:zone] init];
copy.field1 = [[self.field1 copyWithZone:zone] autorelease];
copy.field2 = [[self.field2 copyWithZone:zone] autorelease];
copy.field3 = [[self.field3 copyWithZone:zone] autorelease];
copy.field4 = [[self.field4 copyWithZone:zone] autorelease];
return copy;
}
- (void)dealloc{
[field1 release];
[field2 release];
[field3 release];
[field4 release];
[super dealloc];
}
@end
下面是一个controller 来实现如何持久化自定义类
#import <UIKit/UIKit.h>
//#define kFilename @"data.plist"
#define kFilename @"archive"
#define kDataKey @"Data"
//define kFilename @"dataarchiive.plist"
//#define kDataKey @"Data"
//#define kFilename @"data.sqlite3"
@interface PersistenceViewController : UIViewController {
}
@property (nonatomic,retain) IBOutlet UITextField *field1;
@property (nonatomic,retain) IBOutlet UITextField *field2;
@property (nonatomic,retain) IBOutlet UITextField *field3;
@property (nonatomic,retain) IBOutlet UITextField *field4;
- (NSString *)dataFilePath;
- (void)applicationWillResignActive:(NSNotification *)notification;
@end
#import "PersistenceViewController.h"
#import "FourLines.h"
@implementation PersistenceViewController
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
- (NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"Document Path:%@",documentsDirectory);
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
/*
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
field1.text = [array objectAtIndex:0];
field2.text = [array objectAtIndex:1];
field3.text = [array objectAtIndex:2];
field4.text = [array objectAtIndex:3];
[array release];
*/
//encoding
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
FourLines *fourLines = [unarchiver decodeObjectForKey:kDataKey];
[unarchiver finishDecoding];
field1.text = fourLines.field1;
field2.text = fourLines.field2;
field3.text = fourLines.field3;
field4.text = fourLines.field4;
[unarchiver release];
[data release];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
[super viewDidLoad];
}
- (void) applicationWillResignActive:(NSNotification *)notification{
/*
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:field1.text];
[array addObject:field2.text];
[array addObject:field3.text];
[array addObject:field4.text];
[array writeToFile:[self dataFilePath] atomically:YES];
*/
FourLines *fourLine = [[FourLines alloc] init];
fourLine.field1 = field1.text;
fourLine.field2 = field2.text;
fourLine.field3 = field3.text;
fourLine.field4 = field4.text;
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:fourLine forKey:kDataKey];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
[fourLine release];
[data release];
[archiver release];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[field1 release];
[field2 release];
[field3 release];
[field4 release];
[super dealloc];
}
@end
作者:心不蒙尘
出处:http://www.cnblogs.com/stan0714/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-心不蒙尘。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述