ios24-数据持久化-对象归档
1.创建一个单例模式
//
// ios24_saveObjectToFileViewController.h
// ios24-saveObjectToFile
//
// Created by on 13-6-18.
// Copyright 2013年 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ios24_saveObjectToFileViewController : UIViewController<UITextFieldDelegate>
{
UITextField *tfId;
UITextField *tfName;
UITextField *tfClass;
}
@property (nonatomic,retain) IBOutlet UITextField *tfId;
@property (nonatomic,retain) IBOutlet UITextField *tfName;
@property (nonatomic,retain) IBOutlet UITextField *tfClass;
-(IBAction)save;
-(IBAction)read;
-(NSString *)getFilePath;
@end
----------------------------------------------
//
// ios24_saveObjectToFileViewController.m
// ios24-saveObjectToFile
//
// Created by on 13-6-18.
// Copyright 2013年 __MyCompanyName__. All rights reserved.
//
#import "ios24_saveObjectToFileViewController.h"
#import "Student.h"
@implementation ios24_saveObjectToFileViewController
@synthesize tfId,tfName,tfClass;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
//保存数据
-(IBAction)save{
//实现保存
NSString *savePath=[self getFilePath];
//定义data
NSMutableData *data=[[NSMutableData alloc]init ];
//定义压缩的工具类
NSKeyedArchiver *archer=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
//保存的对象
Student *stu=[[Student alloc]init];
stu.studentId=tfId.text;
stu.studentName=tfName.text;
stu.studentClass=tfClass.text;
//压缩
[archer encodeObject:stu forKey:@"stuobj"];
[archer finishEncoding];
//写入文件
[data writeToFile:savePath atomically:YES];
NSLog(@"保存成功");
}
//读取数据
-(IBAction)read{
//获取path
NSString *readPath=[self getFilePath];
//获取文件的二进制流
NSData *data=[[NSData alloc]initWithContentsOfFile:readPath];
if (data.length>0) {
相关新闻>>
- 发表评论
-
- 最新评论 更多>>