博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ios序列化最终方案
阅读量:7224 次
发布时间:2019-06-29

本文共 7275 字,大约阅读时间需要 24 分钟。

最近在整合一些与服务器交互的东西,准备使用序列化的一些东西

 

使用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 

转载于:https://www.cnblogs.com/stan0714/archive/2012/03/26/2418327.html

你可能感兴趣的文章
《UML用户指南(第2版.修订版)》—第2章2.4节软件开发生命周期
查看>>
《师兄教你找工作——100场面试 20个offer背后的求职秘密》一2.5 那些老生常谈的问题...
查看>>
人类基因编辑国际峰会周琪院士谈基因编辑的未来
查看>>
苹果公然与FBI叫板背后:美国大哥都监控了什么?
查看>>
《Axure RP8 网站和APP原型制作 从入门到精通》一1.3 总结
查看>>
《jQuery Cookbook中文版》——1.1 在HTML页面中包含jQuery程序库代码
查看>>
《 软件测试价值提升之路》——第3章 拦截缺陷 3.1 用户无法正常使用
查看>>
《Android 应用案例开发大全(第二版)》——2.8节工具常量类
查看>>
《JavaScript设计与开发新思维》——1.6 JavaScript版本和浏览器支持
查看>>
网卡,进程绑定cpu
查看>>
常用工具
查看>>
AliSQL 内核定制方案
查看>>
数据结构是哈希表(hashTable)
查看>>
《云周刊》第120期:麒麟来了!PUE逼近1.0,阿里展示液冷黑科技
查看>>
Sed&awk笔记之sed篇:sed基础命令
查看>>
opencv版本记录
查看>>
在大数据时代,该学会什么
查看>>
CSP的今世与未来
查看>>
【阿里招聘】阿里星亲述|凭啥拿到阿里顶级校招offer?
查看>>
CSS清除浮动和定位
查看>>