13-1 iOS 数据持久化

1. writeToFile

    指可以普通的数组 字典
    NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *personsArrPath = [path stringByAppendingString:@"/personsArr.plist"];
    BOOL iswriteSucess = [@[@"222"] writeToFile:personsArrPath atomically:YES];
    NSLog(@"writeToFile  %d",iswriteSucess);
    
    NSArray *fileArr = [NSArray arrayWithContentsOfFile:personsArrPath];
    NSLog(@"fileArr: %@",fileArr);

2. 归档反归档

    NSString *filename = [path stringByAppendingPathComponent:@"downloadModelArray"];
    BOOL isarchiveSucess = [NSKeyedArchiver archiveRootObject:_dataArr toFile:filename];
    NSLog(@"archive  %d",isarchiveSucess);
    
    NSArray *archiveArr = [NSKeyedUnarchiver unarchiveObjectWithFile:filename];
    NSLog(@"archiveArr: %@",archiveArr);

归档反归档需要遵循 协议。NSString  本身遵循这个协议
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:self.downloadStr forKey:@"downloadStr"];
    [aCoder encodeObject:self.downloadedStr forKey:@"downloadedStr"];
    [aCoder encodeObject:self.imageName forKey:@"imageName"];
    [aCoder encodeInteger:self.downloadState forKey:@"downloadState"];

}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self)
    {
        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.downloadStr = [aDecoder decodeObjectForKey:@"downloadStr"];
        self.downloadedStr = [aDecoder decodeObjectForKey:@"downloadedStr"];
        self.imageName = [aDecoder decodeObjectForKey:@"imageName"];
        self.downloadState = [aDecoder decodeIntegerForKey:@"downloadState"];
    }
    return self;
}

3. NSUserDefaults

+ (void)savePhoneNumber:(NSString *)phoneNumber {
    [[NSUserDefaults standardUserDefaults] setObject:phoneNumber forKey:phoneNumberKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
+ (NSString *)getPhoneNumber {
   return [[NSUserDefaults standardUserDefaults] objectForKey:phoneNumberKey];
}

4. Core Data

5. SQLite3 FMDB Realm[简单 也是基于数据库]

你可能感兴趣的:(13-1 iOS 数据持久化)