Data storage and IO (ii)

Source: Internet
Author: User

One, NSBundle resource bundle.

Just drag the file to the left of the Xcode project navigation panel, select Copy file to project, and the file will be included in the bundle. Use [NSBundle Mainbundle] to get the application package, common methods:

    • Urlforresource:withextension: Gets the corresponding URL based on the resource name and extension.
    • Pathforresource:oftype: Gets the corresponding path based on the resource name and the type name.
    • ResourcePath: Returns the full path of the resource contained in the NSBundle subdirectory.

Second, Nskeyedarchiver, nskeyedunarchiver archiving and recovery.

Archiving is a format in which one or more objects are saved to a specified file (converting objects into a data stream that can be saved, transportable), and then recovered from the file when needed (restoring the object from the data stream).

Nskeyedarchiver and nskeyedunarchiver inherit from Nscoder.

1. Simple usage of nskeyedarchiver (for non-custom OC objects).

  • Call Nskeyedarchiver's Archiverootobject:tofile: Class method directly, specifying that the single object be archived for root.
    1Nsdictionary *dict = @{@"Xiaohong":@"Little Red",@"xiaoming":@"Xiao Ming"};2NSString *path =nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES). Lastobject;3Path = [path stringbyappendingpathcomponent:@"Dict.arch"];4BOOL ISSUCC = [Nskeyedarchiver archiverootobject:dict Tofile:path];
  • Or call Nskeyedarchiver's Archiveddatawithrootobject: Class method, convert a single object to a NSData type and return, and then write to the local or network.
    1Nsdictionary *dict = @{@"Xiaohong":@"Little Red",@"xiaoming":@"Xiao Ming"};2NSData *data =[Nskeyedarchiver archiveddatawithrootobject:dict];3NSString *path =nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES). Lastobject;4Path = [path stringbyappendingpathcomponent:@"Data.arch"];5[Data Writetofile:path Atomically:yes];
  • Directly call Nskeyedunarchiver's Unarchiveobjectwithfile: Class method to recover.
  •    1  nsstring *path = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES). Lastobject;  2  path = [path Stringbyappendingpathcomponent:@ " dict.arch  "  ]; 3  nsdictionary *dict = [Nskeyedunarchiver Unarchiveobjectwithfile:path];  
  • Or call Nskeyedunarchiver's Unarchiveobjectwithdata: Class method to restore a single object that has been archived to NSData.
    1 nsstring *path = nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES). Lastobject; 2 Path = [path stringbyappendingpathcomponent:@ "data1.arch"]; 3 NSData *data = [NSData Datawithcontentsoffile:path]; 4 nsdictionary *dicts = [Nskeyedunarchiver unarchiveobjectwithdata:data];

2. Usage of the Nscoding protocol (for custom OC objects).

If a program needs to archive or restore any custom object, the class must implement the Nscoding protocol and implement the methods defined in the protocol.

  • 1 #import <UIKit/UIKit.h>23@interface hlperson:nsobject <NSCoding> 4 5 @property (copy, nonatomic) NSString *name; 6 @property (Assign, nonatomic) cgfloat height; 7 8 @end
  • When you archive this object, you always call the Encodewithcoder: method, which in this method calls Nscoder's Encodexxx:forkey: method to archive the corresponding member variable.
  • When you reply to the object, you always call the Initwithcoder: method, which in this method calls Nscoder's Decodexxxforkey: method to recover the value of the corresponding member variable.
    1 #import "HLPerson.h"2 3 @implementationHlperson4 5- (void) Encodewithcoder: (Nscoder *) Acoder {6[Acoder encodeObject:self.name Forkey:@"name"];7[Acoder encodeFloat:self.height Forkey:@"Height"];8 }9 Ten-(Instancetype) Initwithcoder: (Nscoder *) Adecoder { OneSelf.name = [Adecoder decodeobjectforkey:@"name"]; ASelf.height = [Adecoder decodefloatforkey:@"Height"]; -     returnSelf ; - } the  - @end

Then you can archive our custom Hlperson objects just like you would archive a normal object, see 1.

3, with NSData Custom archive.

The previous method can only archive or restore a single OC object, and to archive or restore multiple objects into a single file, you could use Nsmutabledata to create Nskeyedarchiver or Nskeyedunarchiver objects.

(1), archiving steps.

  • Creates a Nskeyedarchiver object with Nsmutabledata as a parameter.
  • Repeatedly call the Encodexxx:forkey: Method of the Nskeyedarchiver object to archive all objects that need to be archived to a file.
  • Call the Finishencoding method of the Nskeyedarchiver object to end the archive.
  • Save the Nsmutabledata object to a local or network.
    1Hlperson *person =[[Hlperson alloc] init];//custom objects need to implement Nscoding protocol2Person.name =@"Hahh";3Person.height = -;4 5Nsdictionary *dict = @{@"Xiaohong":@"Little Red",@"xiaoming":@"Xiao Ming"};6Nsarray *array =@[person, dict];7CGFloat age =12.5;8 9Nsmutabledata *data =[Nsmutabledata data];TenNskeyedarchiver *arch =[[Nskeyedarchiver alloc] initforwritingwithmutabledata:data]; One[Arch Encodeobject:person Forkey:@" Person"]; A[Arch encodeobject:dict Forkey:@"Dict"]; -[Arch Encodeobject:array Forkey:@"Array"]; -[Arch Encodefloat:age Forkey:@" Age"]; the [Arch finishencoding]; -  -NSString *path =nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES). Lastobject; -Path = [path stringbyappendingpathcomponent:@"Data.arch"]; +BOOL ISSUCC = [data Writetofile:path atomically:yes];

(2), recovery steps.

  • Creates a Nskeyedunarchiver object with NSData as a parameter.
  • Call the Decodexxx:forkey: Method of the Nskeyedunarchiver object repeatedly to recover all archived objects from a file.
  • Call the Finishencoding method of the Nskeyedunarchiver object to end the recovery.
    1NSString *path =nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES). Lastobject;2Path = [path stringbyappendingpathcomponent:@"Data.arch"];3NSData *data =[NSData Datawithcontentsoffile:path];4Nskeyedunarchiver *unarch =[[Nskeyedunarchiver alloc] initforreadingwithdata:data];5 6Hlperson *person = [Unarch decodeobjectforkey:@" Person"];7Nsdictionary *dict = [Unarch decodeobjectforkey:@"Dict"];8Nsarray *array = [Unarch decodeobjectforkey:@"Array"];9CGFloat age = [Unarch Decodefloatforkey:@" Age"];Ten  One[Unarch finishdecoding];

Extension: The archive converts the entire object into byte data, including all member variables of the object, and if the member variable points to another OC object, the OC object is also archived together into byte data. This means that when a program archives an object, all data associated with that object is converted to byte data. If the program recovers objects from these byte data, the recovered object is the same as the original object, but the address is different in memory, which implements the deep copy of the object.

Data storage and IO (ii)

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.