IOS data persistence-plist

Source: Internet
Author: User

IOS data persistence-plist

 

The previous article mentioned how to use NSUserDefaults to store user preferences. This article describes how to use plist and common files to store structured data, generally, Plist is used to store data that does not require structured queries, and CoreData is usually used for structured queries. After all, it is easier to query data based on databases. Hope that readers can learn this article

How to use a program to read and write plist how to create a directory library directory and a document directory to save the custom model class to plist
Library directory and document directory

I have previously written the differences between the two directories. I will mention the differences here:

Document is the data files exposed to users, which are visible to users and can be read and written;

The library directory is a data file managed by the App for users and is transparent to users. Therefore, files that users cannot access explicitly must be stored here and can be read and written.

Obtain the Library directory

NSFileManager * defaultManager = [NSFileManager defaultManager];    NSURL * applicationSupportPath = [[defaultManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask]firstObject];

Get Document directory

  NSFileManager * defaultManager = [NSFileManager defaultManager];    NSURL * applicationSupportPath = [[defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]firstObject];
Read and Write Plist

Plist files are structured data files stored in iOS, which are easy to read (returned by Array and Dictionary ).
Write files

    NSArray * array = @[@1,@2,@3,@4];    NSFileManager * defaultManager = [NSFileManager defaultManager];    NSURL * documentPath = [[defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]firstObject];    NSString * fileSavePath = [documentPath.path stringByAppendingPathComponent:@file.plist];    BOOL success =  [array writeToFile:fileSavePath atomically:YES];

After writing the code, check the sandbox of the simulator-writing successful. Of course, the return value of the above Code success can also determine whether the writing is successful.

Read files

    NSFileManager * defaultManager = [NSFileManager defaultManager];    NSURL * documentPath = [[defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]firstObject];    NSString * fileSavePath = [documentPath.path stringByAppendingPathComponent:@file.plist];    NSArray * array = [NSArray arrayWithContentsOfFile:fileSavePath];    NSLog(@%@,array);

Note: If the file of the above Code does not exist, the read result is nil. You do not need to determine whether or not it exists.

How to create a directory?

When writing files to a new directory, you must determine whether the directory exists. Otherwise, the program will crash.
Use functions to determine

 - (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory

If not, create a path

 - (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error
CreateIntermediates is used to create all non-existing parent directories, such :... Document/DicA/DicB/file.txt automatically creates multi-level directories. Attributes is generally nil, which is used to set permissions. nil indicates the default permissions.

For example
Write Data to the Application Support/Demo/directory. If this directory does not exist, create

 NSDictionary * dic = @{@name:@Wenchenhuang,@URL:@blog.csdn.net/hello_hwc?viewmode=list};    NSFileManager * defaultManager = [NSFileManager defaultManager];    NSURL * libraryPath = [[defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask]firstObject];    NSString * fileContainFloder = [libraryPath.path stringByAppendingPathComponent:@DemoData];    BOOL isDic = YES;    if (![defaultManager fileExistsAtPath:fileContainFloder isDirectory:&isDic]) {        [defaultManager createDirectoryAtPath:fileContainFloder withIntermediateDirectories:YES attributes:nil error:nil];    }    NSString * fileSavePath = [fileContainFloder stringByAppendingPathComponent:@file.plist];    BOOL success =  [dic writeToFile:fileSavePath atomically:YES];

Check the sandbox.

The Application Support directory is a sub-directory of the Library. From the documentation, this directory is used to store common data that is transparent to users. CoreData can be stored here.

How to save a custom Model

Generally, to write a custom Model to a plist file in a simple way, followNSCodingProtocol. Then NSKeyedArchiver is used for encoding to generate NSData. After reading the data, NSUnKeyedArchiver is used for decoding.
Define a Model

A custom Model can be implemented in many places, such as the NSCopying protocol, hash, and isEqual functions. You can also use a third-party library, which is beyond the scope of this article, in the future, I will explain how to write a Model class. Here we will know the NSCoding protocol.

#import 
  
   @interface DemoUser : NSObject
   
    @property (copy,nonatomic) NSString * name;@property (copy,nonatomic) NSString * uniqueID;-(instancetype)initWithName:(NSString *)name UnqiueID:(NSString *)uniqueID;@end
   
  
# Import deshortname. h @ implementation deshortname // two required implementation methods of the Protocol-(instancetype) initWithCoder :( NSCoder *) aDecoder {self = [super init]; if (! Self) {return nil;} _ uniqueID = [aDecoder decodeObjectForKey: @ KUnqiueID]; _ name = [aDecoder decodeObjectForKey: @ KName]; return self ;}- (void) encodeWithCoder :( NSCoder *) acder {-(void) encodeWithCoder :( NSCoder *) acder {if (self. name! = Nil) {[ecoder encodeObject: self. name forKey: @ KName];} if (self. uniqueID! = Nil) {[aCoder encodeObject: self. uniqueID forKey: @ KUnqiueID] ;}// an initialization method-(instancetype) initWithName :( NSString *) name UnqiueID :( NSString *) uniqueID {if (self = [super init]) {_ name = name; _ uniqueID = uniqueID;} return self ;}@ end

Save

    DemoUser * user = [[DemoUser alloc] initWithName:@wenchenhuang UnqiueID:@123456];    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];    [dic setObject:@1.0  forKey:@version];    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:user];    [dic setObject:data forKey:@user];    //Get path    NSFileManager * defaultManager = [NSFileManager defaultManager];    NSURL * applicationSupportPath = [[defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask]firstObject];    NSString * fileContainFloder = [applicationSupportPath.path stringByAppendingPathComponent:@DemoData];    BOOL isDic = YES;    if (![defaultManager fileExistsAtPath:fileContainFloder isDirectory:&isDic]) {        [defaultManager createDirectoryAtPath:fileContainFloder withIntermediateDirectories:YES attributes:nil error:nil];    }    NSString * fileSavePath = [fileContainFloder stringByAppendingPathComponent:@user.plist];    BOOL success =  [dic writeToFile:fileSavePath atomically:YES];

Read

    NSFileManager * defaultManager = [NSFileManager defaultManager];    NSURL * applicationSupportPath = [[defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask]firstObject];    NSString * filePath = [applicationSupportPath.path stringByAppendingPathComponent:@DemoData/user.plist];    NSDictionary * dic = [NSDictionary dictionaryWithContentsOfFile:filePath];    NSString * version = [dic objectForKey:@version];    NSData * data = [dic objectForKey:@user];    DemoUser * user = [NSKeyedUnarchiver unarchiveObjectWithData:data];    NSLog(@%@ %@,user.name,user.uniqueID);

This is part of my blog's iOS directory. Maybe you can find the desired content here.
Http://blog.csdn.net/hello_hwc/article/details/45365385

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.