您的位置:首页 > 移动开发 > IOS开发

IOS 数据持久化只归档与取消归档

2014-01-07 16:08 288 查看
以前在学习OC的时候归档这一块老师偷懒没有讲,给我造成了很大的麻烦,总感觉这一块不熟悉,看书的话,这一个知识点都看了好几遍,还是没有掌握,最近我又重新来了一边,对于归档有了自己的一些心得,特来给大家分享一下,另外呢,还有一个代码,里面有完整版的归档,和取消归档,我个人感觉这个代码很经典,值得大家收藏哦,网上的理论讲的很多,我的博客里面有转载的讲的比较好的,这里就不说了,我主要和大家分享一下,这个程序。

通过控件拖拽的方式,在storyboard里面,建立如下界面:



并对相关控件创建必要的连接。接下来时代码的分享,如果大家不懂的话,百度一下就OK了。忘了说了我用的时Xcode5,用了storyboard,如果低于这个版本的话,前两个文件里面的代码不用管,建立一个单视图工程,即可。AppDelegate.h和AppDelegate.m,不用管了,直接看后面的就行了。

HHLAppDelegate.h

#import <UIKit/UIKit.h>

@interface HHLAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end


HHLAppDelegate.m
#import "HHLAppDelegate.h"

@implementation HHLAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


myClass.h
#import <Foundation/Foundation.h>

@interface myClass : NSObject<NSCoding>

@property (strong,nonatomic)NSString *name;
@property (assign,nonatomic)int age;
@property (assign,nonatomic)BOOL sex;

@end


myClass.m
#import "myClass.h"

@implementation myClass

- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];

[aCoder encodeInteger:self.age forKey:@"age"];

[aCoder encodeBool:self.sex forKey:@"sex"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.sex = [aDecoder decodeBoolForKey:@"sex"];

}
return self;
}

@end


HHLViewController.h
#import <UIKit/UIKit.h>
#import "myClass.h"
//#define AppDocuments [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

@interface HHLViewController : UIViewController<UITextFieldDelegate>
{
myClass *class1;
}
@property (strong, nonatomic) IBOutlet UITextField *tfName;
@property (strong, nonatomic) IBOutlet UITextField *tfAge;
@property (strong, nonatomic) IBOutlet UISegmentedControl *segSex;
@property (strong, nonatomic) IBOutlet UIButton *button;

- (IBAction)archiveUnarchive:(id)sender;

- (myClass *)makemyClassInstance;
@end


HHLViewController.m

#import "HHLViewController.h"
//#import "myClass.h"

@interface HHLViewController ()

@end

@implementation HHLViewController

- (void) init:(myClass *)class//主要是取消归档时显示用的
{
if (class == nil) {
self.tfName.text = nil;
self.tfAge.text = nil;
self.segSex.selectedSegmentIndex = 0;
}
else{
self.tfName.text = class.name;
self.tfAge.text = [NSString stringWithFormat:@"%d",class.age];
self.segSex.selectedSegmentIndex = class.sex;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self init:nil];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- (IBAction)archiveUnarchive:(id)sender {
self.button.enabled = NO;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"%@",path);
NSString *filePath = [path stringByAppendingPathComponent:@"customobject.txt"];
class1 = [[myClass alloc] init];
if (self.button.tag == 0) {
if (self.tfName && self.tfName.text.length >0 && self.tfAge && self.tfAge.text.length >0) {
self.button.tag = 1;
[self.button setTitle:@"反归档" forState:UIControlStateNormal];
[self makemyClassInstance];
[NSKeyedArchiver archiveRootObject:class1 toFile:filePath];
[self init:nil];
}
}
else
{
self.button.tag = 0;
[self.button setTitle:@"归档" forState:UIControlStateNormal];
class1 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
[self init:class1];
}
self.button.enabled = YES;
}

- (myClass *)makemyClassInstance//归档时调用这个函数
{
class1.name = self.tfName.text;
class1.age = [self.tfAge.text intValue];
class1.sex =self.segSex.selectedSegmentIndex != 0;

return class1;
}

- (void) dealloc
{
[class1 release];
[_button release];
[_tfAge release];
[_tfName release];
[_segSex release];
[super dealloc];
}
@end


运行后的效果如下图所示:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息