Object-c  数据存储的方法

来源:互联网 发布:蓝牙耳机软件 编辑:程序博客网 时间:2024/05/22 13:34

如果数据存储对象是NSString,NSDictionary,NSArray,NSDate,NSData或者NSNumber,可以使用这些类的 writeToFile:atomically:方法来存储。用这种方法保存dictionary,array的数据是按照XML格式的文件存储的。

实例:

////  main.m//  Program191////  Created by Kennyliang on 12-9-5.//  Copyright (c) 2012年 Kennyliang. All rights reserved.//#import <Foundation/Foundation.h>int main(int argc, const char * argv[]){    @autoreleasepool {                // insert code here...        NSLog(@"Hello, World!");        NSDictionary    *glossary = [NSDictionary dictionaryWithObjectsAndKeys:@"A class defined so other classes can inherit from it.",@"abstract class",@"To implement all the methods defined in a protocol",@"adopt",@"Storing an object for later use.",@"archiving", nil];              if ([glossary writeToFile:@"glossary" atomically:YES] == NO)        {            NSLog(@"Save to file failed!");        }            }    return 0;}
atomically参数如果设置为YES,那么数据会先写入到一个临时文件中,当存储成功的时候,再移动到目的地。这样可以防止当数据存储到一半的时候,忽然发生错误,原来的glossary被毁坏。

存储后,glossary的文件内容为:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>abstract class</key>
    <string>A class defined so other classes can inherit from it.</string>
    <key>adopt</key>
    <string>To implement all the methods defined in a protocol</string>
    <key>archiving</key>
    <string>Storing an object for later use.</string>
</dict>
</plist>


当从一个dictionary创建property list的时候,所有的key值必须是NSString对象,dictionary的value值可以是NSString,NSArray,NSDictionary,NSData,NSDate,NSNumber对象。

将数据从文件读取回来,可以使用dictionaryWithContentsOfFile:或者arrayWithContentsOfFile:或者dataWithContentsOfFile:或者stringWithContentsOfFile:


读取的例子:

////  main.m//  Program191////  Created by Kennyliang on 12-9-5.//  Copyright (c) 2012年 Kennyliang. All rights reserved.//#import <Foundation/Foundation.h>int main(int argc, const char * argv[]){    @autoreleasepool {                // insert code here...        NSLog(@"Hello, World!");        NSDictionary    *glossary = [NSDictionary dictionaryWithObjectsAndKeys:@"A class defined so other classes can inherit from it.",@"abstract class",@"To implement all the methods defined in a protocol",@"adopt",@"Storing an object for later use.",@"archiving", nil];              if ([glossary writeToFile:@"glossary" atomically:YES] == NO)        {            NSLog(@"Save to file failed!");        }                NSDictionary   *glossaryBack = [NSDictionary dictionaryWithContentsOfFile:@"glossary"];        for(NSString *key in glossaryBack)        {            NSLog(@"%@: %@",key,[glossaryBack objectForKey:key]);        }            }    return 0;}

使用NSKeyedArchiver来存储数据:

////  main.m//  Program193////  Created by Kennyliang on 12-9-5.//  Copyright (c) 2012年 Kennyliang. All rights reserved.//#import <Foundation/Foundation.h>int main(int argc, const char * argv[]){    @autoreleasepool {                // insert code here...        NSLog(@"Hello, World!");        NSDictionary    *glossary = [NSDictionary dictionaryWithObjectsAndKeys:@"A class defined so other classes can inherit from it",@"abstract class",@"To implement all the methods defined in a protocol",@"adopt",@"Storing an object for later use",@"archiving",nil];                [NSKeyedArchiver archiveRootObject:glossary toFile:@"glossary.archive"];                NSDictionary    *glossaryBack = [NSKeyedUnarchiver unarchiveObjectWithFile:@"glossary.archive"];        for (NSString *key in glossaryBack)        {            NSLog(@"%@:%@",key,[glossaryBack objectForKey:key]);        }            }    return 0;}

通过这种方法存储的对象必须实现<NSCoding> protocol.

示例:

-(void)encodeWithCoder:(NSCoder*)encoder{    [encoder encodeObject:name forKey:@"AddressCardName"];    [encoder encodeObject:email forKey:@"AddressCardEmail"];}-(id)initWithCoder:(NSCoder*)decoder{   name = [[decoder decodeObjectforKey:@"AddressCardName"] retain];   email = [[decoder decodeObjectforKey:@"AddressCardEmail"] retain]; return self;}

如果是基本数据类型

可以使用

 

Encoder Decoder

encodeBool:forKey:       decodeBool:forKey:
encodeInt:forKey:        decodeInt:forKey:
encodeInt32:forKey:      decodeInt32:forKey:
encodeInt64: forKey:     decodeInt64:forKey:
encodeFloat:forKey:      decodeFloat:forKey:
encodeDouble:forKey:     decodeDouble:forKey:


原创粉丝点击