随笔 - 21  文章 - 2  评论 - 36  阅读 - 93260

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 

posted on   心不蒙尘  阅读(2238)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
< 2012年3月 >
26 27 28 29 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
1 2 3 4 5 6 7

点击右上角即可分享
微信分享提示