plist存储的用法和路径


//plist存储,只能存储一般的对象
-(void)saveArray
{
//1.获得沙河路径
NSString *home=NSHomeDictory();
//2.documnet路径
NSString *docPath=[home stringBuAppedingPathCompent:@“Document”];
//3.新建数据
NSArray *data=@[@“dvsgvdf”,@198,@“vfgrvfer”];
//
NSString *filepath=[docPath stringByAppendingPathCompent:@“data.plist”];
[filepath writeToFile:filepath atomicolly:YES];




//用途,快速存储键值对,不需要创建文件夹和文件名,只需要告诉他UserDefault来存就行了;这就是偏好设置,缺点是不能改文件夹和文件名,只能写在preference文件夹里面
-(IBAction)save{
NSUerDefaults *defaults=[NSUserfault standarUserDefault];

[default setobject:@“cvdeghio” forKey:@“account”];
[default setInteger:10 forKey:@“age”];
[default setBool:Yes forkey:@“auto_login”];
3.//立即同步
[default synchronize];
}






#import "MJStudent.h"



@interface MJStudent()



@end



@implementation MJStudent



/**

 *  将某个对象写入文件时会调用

 *  在这个方法中说清楚哪些属性需要存储

 */

- (void)encodeWithCoder:(NSCoder *)encoder

{

    [encoder encodeObject:self.no forKey:@"no"];

    [encoder encodeInt:self.age forKey:@"age"];

    [encoder encodeDouble:self.height forKey:@"height"];

}



/**

 *  从文件中解析对象时会调用

 *  在这个方法中说清楚哪些属性需要存储

 */

- (id)initWithCoder:(NSCoder *)decoder

{

    if (self = [super init]) {

        // 读取文件的内容

        self.no = [decoder decodeObjectForKey:@"no"];

        self.age = [decoder decodeIntForKey:@"age"];

        self.height = [decoder decodeDoubleForKey:@"height"];

    }

    return self;

}

@end







#import "MJViewController.h"
#import "MJStudent.h"

@interface MJViewController ()
- (IBAction)save;
- (IBAction)read;
@end

@implementation MJViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)save {
    // 1.新的模型对象
    MJStudent *stu = [[MJStudent alloc] init];
    stu.no = @"42343254";
    stu.age = 20;
    stu.height = 1.55;
    
    // 2.归档模型对象
    // 2.1.获得Documents的全路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
    // 2.3.将对象归档
    [NSKeyedArchiver archiveRootObject:stu toFile:path];
}

- (IBAction)read {
    // 1.获得Documents的全路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
    
    // 3.从文件中读取MJStudent对象
    MJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    NSLog(@"%@ %d %f", stu.no, stu.age, stu.height);
}
@end

原文地址:https://www.cnblogs.com/anshinianyujing/p/4542169.html