有时候我们启动某些程序时总需要先填写一些信息才能进行下一步操作,例如登陆界面必需输入一些基本信息进行验证后才能登陆成功,由于每一次启动后都必需手动输入基本固定的信息,所以我们可以实现输入一次信息之后点击保存,下一次程序启动能显示原先的输入信息,就好像qq的记住用户名和密码一样,保存一次成功后就以后启动程序都无需再进行输入。所以以下我就举输入ip地址和端口号为例简单记录:
(1)ArchivingData.h 的定义:
@interface ArchivingData : NSObject <NSCoding, NSCopying>
//以下变量名主要用于保存输入信息
@property (copy, nonatomic) NSString *ip;
@property (copy, nonatomic) NSString *port;
@end
(2)ArchivingData.m 的定义
#define kIdKey @"IdKey"
#define kPortKey @"PortKey"
#define kPasswordKey @"PasswordKey"
@implementation ArchivingData
@synthesize ip;
@synthesize port;
//编码
#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:ip forKey:kIdKey];
[aCoder encodeObject:port forKey:kPortKey];
}
//解码
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
ip = [aDecoder decodeObjectForKey:kIdKey];
port = [aDecoder decodeObjectForKey:kPortKey];
}
return self;
}
//复制
#pragma mark NSCoping
- (id)copyWithZone:(NSZone *)zone {
ArchivingData *copy = [[[self class] allocWithZone:zone] init];
copy.ip = [self.ip copyWithZone:zone];
copy.port = [self.port copyWithZone:zone];
return copy;
}
@end
(3)viewController.m (ps:只标注核心部分)
#define kArchivingFileKey @"archivingFile"
#define kArchivingDataKey @"ArchivingDataKey"
//---------------该模块声明了读取后台文件的一些变量(Begin)-----------------------//
// 创建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//获取应用程序沙盒的Documents目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//得到完整的文件名,使用stringByAppendingPathComponent才会在之前的目录基础上加上/
self.archivingFilePath = [documentsDirectory stringByAppendingPathComponent:kArchivingFileKey];
//---------------该模块声明了读取后台文件的一些变量(End)-----------------------//
因为我采用的是tableViewController,所以我在每一个cell中读取后台文件数据进行显示
//如果归档文件存在,则读取其中内容,显示在界面上
if ([fileManager fileExistsAtPath:self.archivingFilePath]) {
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:self.archivingFilePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
ArchivingData *archivingData = [unarchiver decodeObjectForKey:kArchivingDataKey];
[unarchiver finishDecoding];
if(row == 0)
[[cell textField ] setText: archivingData.ip];
if(row == 1)
[[cell textField ] setText: archivingData.port];
}
//保存输入的内容
- (void)applicationWillResignActive:(NSNotification *)notification{
ArchivingData *archivingData = [[ArchivingData alloc] init];
archivingData.ip = ((UITextField *)[dictionary objectForKey:@"ID号"] ).text;
archivingData.port = ((UITextField *)[dictionary objectForKey:@"端口"] ).text;
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:archivingData forKey:kArchivingDataKey];
[archiver finishEncoding];
[data writeToFile:self.archivingFilePath atomically:YES];
}