Data Persistence, Data
Directly run the Code:
//// AppDelegate. m //// # import "AppDelegate. h "# import" Person. h "@ interface AppDelegate () @ end @ implementation AppDelegate-(void) dealloc {[_ window release]; [super dealloc];}-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {self. window = [[[UIWindow alloc] initWithFrame: [UIScreen mainScreen] bounds] autorelease]; // Override point for cu Stomization after application launch. self. window. backgroundColor = [UIColor whiteColor]; [self. window makeKeyAndVisible]; // This function can determine whether to return the complete path by specifying the directory name (the first parameter), the specified scope (the second parameter), and BOOL parameters, the Return Value Type of this function is array. The returned value is an array because there are several identical directories in the scope. NSArray * filePaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); // the commonly used folder for data persistence is Documents. NSLog (@ "Documents: % @", filePaths. firstObject); // folder commonly used for data persistence: tmp. However, important user data must be stored in the Documents folder. NSString * tmpFilePath = NSTemporaryDirectory (); NSLog (@ "tmp: % @", tmpFilePath); // after the application is installed, an object is generated in the corresponding sandbox. app file (the corresponding class is NSBundle), the resource file in the project will be saved in this. in the app file, this. the app file is read-only. We usually call it an application package. NSString * imagePath = [[NSBundle mainBundle] pathForResource: @ "beutifuly" ofType: @ "jpg"]; NSLog (@ "% @", imagePath ); // obtain the Documents folder path of the stored file NSString * docPath = filePaths. lastObject; // generate text file path strength // NSString * textFilePath = [docPath stringByAppendingString: @ "/text.txt"]; NSString * textFilePath = [docPath stringByAppendingPathComponent: @ "text.txt"]; NSLog (@ "% @", textFilePath); // write a simple object to a file // 1. String writing to a text file NSString * str = @ "string writing to a text file"; [str writeToFile: textFilePath atomically: YES encoding: NSUTF8StringEncoding error: nil]; // 2. NSString * arrayPath = [docPath stringByAppendingPathComponent: @ "array. plist "]; NSLog (@" % @ ", arrayPath); NSArray * array = @ [@" Haha ", @" Haha ", @" ", @ 123]; [array writeToFile: arrayPath atomically: YES]; // 3. dictionary writing file NSString * dictPath = [docPath stringByAppendingPa ThComponent: @ "dict. plist "]; NSDictionary * dict ={ @" name ": @" wang ", @" gender ": @" zhen ", @" Age ": @ 12 }; [dict writeToFile: dictPath atomically: YES]; // 4. NSData Writing File (you can write text strings, audios, videos, images, etc.) NSString * dataPath = [docPath stringByAppendingPathComponent: @ "soYBAFVSEQ2IVhkZAA6sj5uH4wQAAAVIgLO86QADqyn976. m4a "]; NSData * imageData = [NSData dataWithContentsOfURL: [NSURL URLWithString: @" http://fs.open.kugou.com/3a25cd93b 65ac6611a2503dd8ad67976/24/60/48 18/M08/0A/17/soYBAFVSEQ2IVhkZAA6sj5uH4wQAAAVIgLO86QADqyn976. m4a "]; [imageData writeToFile: dataPath atomically: YES]; NSLog (@" % @ ", dataPath ); // use NSFileManager to manage files // 1. Create a folder NSFileManager * filManager = [NSFileManager defaultManager]; [filManager createDirectoryAtPath: [docPath stringByAppendingPathComponent: @ "xxx"] metadata: YES attributes: Nil error: nil]; // you should first determine whether the file corresponding to the path strength exists. If yes, read the file content first, splice the new content, and then write it into the file. NSString * contentStr = nil; // use the file management object to determine whether the specified file path strength exists if ([filManager fileExistsAtPath: textFilePath]) {contentStr = [NSString stringWithContentsOfFile: textFilePath encoding: NSUTF8StringEncoding error: nil];} else {contentStr = [NSString];} // concatenate a new string contentStr = [contentStr stringByAppendingString: @ "\ n hahaha Hahahaha"]; // re-write the concatenated string to the file (this method occupies too much memory and should use the File pointer NSFileHanle to operate the file) [contentStr writ EToFile: textFilePath atomically: YES encoding: NSUTF8StringEncoding error: nil]; // NSMutableArray * personList = [NSMutableArray array] for (int I = 0; I <100; I ++) {Person * aPerson = [[Person alloc] init] autorelease]; aPerson. name = @ "wang"; aPerson. gender = @ "male"; aPerson. age = 123; [personList addObject: aPerson];} // specify the file path NSString * arcPath = [docPath stringByAppendingPathCo Mponent: @ "person. arc "]; // use an archive object to archive the corresponding data [NSKeyedArchiver archiveRootObject: personList toFile: arcPath]; // use an archive class, get archived data // Person * person = [NSKeyedUnarchiver unarchiveObjectWithFile: arcPath]; // NSLog (@ "% @, % @, % ld", person. name, person. gender, person. age); NSArray * person = [NSKeyedUnarchiver unarchiveObjectWithFile: arcPath]; NSLog (@ "% @", person); // return the Home Directory of the current application, that is, the sandbox directory. NSString * homePath = NSHomeDirectory (); NSLog (@ "% @", homePath); return YES ;}- (void) applicationWillResignActive :( UIApplication *) application {// Sent when the application is about to move from active to inactive state. this can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. games shocould use this method to pause the game .} -(void) applicationDidEnterBackground :( UIApplication *) application {// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits .} -(void) applicationWillEnterForeground :( UIApplication *) application {// Called as part of the transition from the background to the inactive state; here you can undo records of the changes made on entering the background .} -(void) applicationDidBecomeActive :( UIApplication *) application {// Restart any tasks that were paused (or not yet started) while the application was inactive. if the application was previusly in the background, optionally refresh the user interface .} -(void) applicationWillTerminate :( UIApplication *) application {// Called when the application is about to terminate. save data if appropriate. see also applicationDidEnterBackground :.} @ end
/// Person. h ///// # import <Foundation/Foundation. h> @ interface Person: NSObject <NSCoding> // If a custom Class Object supports archiving, it must comply with the NSCoding Protocol and implement the encoding and decoding protocols. @ Property (nonatomic, retain) NSString * name; @ property (nonatomic, retain) NSString * gender; @ property (nonatomic, assign) NSInteger age; @ end // Person
/// Person. m /// # import "Person. h "@ implementation Person // The encoding protocol is used to convert objects of the current class to NSData-(void) encodeWithCoder :( NSCoder *) acder {[ACO encodeObject: self. name forKey: @ "NAME"]; [ecoder encodeObject: self. gender forKey: @ "GENDER"]; [ecoder encodeInteger: self. age forKey: @ "AGE"];} // decoding method, called when NSData type data is converted to the object of the current class during Reverse archiving. The key used for decoding must be consistent with the key specified for encoding. -(Id) initWithCoder :( NSCoder *) aDecoder {if (self = [super init]) {self. name = [aDecoder decodeObjectForKey: @ "NAME"]; self. gender = [aDecoder decodeObjectForKey: @ "GENDER"]; self. age = [aDecoder decodeIntegerForKey: @ "AGE"];} return self ;}@ end
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.