The sandbox mechanism of data localization

Source: Internet
Author: User
Tags string to file

1. What is sandbox mechanism (sandbox)? Each iOS application creates a file system directory (folder) for itself, a separate, closed, and secure space called a sandbox.

Note: 1. Each application will have an application sandbox. 2. Each program sandbox is a file system directory.

2. Features of the sandbox

3. Sandbox folders and the role of individual folders

4. Simple data type written locally (string, array, dictionary, nsdata type of data stored locally)

#pragma mark-local persistence for simple objects

#pragma mark-stores data of type NSString to local
1. Need to know where this object exists, so a path to a folder is required
2. Find Documents folder path
NSString *documentpath = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) OBJECTATINDEX:0];
3. We need to know what to store. So what to create
Create the content to store: string
NSString *str = @ "Liuaoran";
4. Need to know where the string is ultimately stored, so you need to create a path to store the string
NSString *strpath = [documentpath stringbyappendingpathcomponent:@ "Leikun.txt"];

5. Prepare to complete, write string to file
First parameter: The path to the file being written
The second parameter: in the case of a power outage, will not automatically save
Third parameter: encoding format nsutf8stringencoding
The fourth parameter:
[Str writetofile:strpath atomically:yes encoding:nsutf8stringencoding Error:nil];

NSLog (@ "strpath =%@", strpath);

#pragma mark-Take out the contents of the NSString folder store
Remove a string
Stringwithcontentsoffile This method to take it out
First parameter: The path of the string store
Second parameter: encoding format
Third parameter: Error message
NSString *newstr = [NSString stringwithcontentsoffile:strpath encoding:nsutf8stringencoding Error:nil];
NSLog (@ "newstr =%@", newstr);

#pragma mark-stores data of type Nsarray to local
1. Locate the folder path where the object resides
NSString *documentpath1 = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) OBJECTATINDEX:0];
2. Create an array to store
Nsarray *array = @[@ "Black", @ "Mbboy", @ "Seabrother", @ "bpy", @ "BOOM"];
3. Creating an array storage final path
NSString *arraypath = [documentPath1 stringbyappendingpathcomponent:@ "Leikun.plist"];
4. Writing an array to a file
[Array Writetofile:arraypath atomically:yes];

NSLog (@ "Arraypath =%@", Arraypath);

A local array will be available for removal
Nsarray *newarray = [Nsarray Arraywithcontentsoffile:arraypath];
NSLog (@ "NewArray =%@", NewArray);

#pragma mark-stores data of type nsdictionary to local
1. Locate the folder path where the object resides
NSString *documentpath2 = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) OBJECTATINDEX:0];
2. Create a dictionary to store
Nsdictionary *dictionarypath = @{
@ "name": @ "Leikun",
@ "Age": @18,
@ "Hobby": @ "basketball",
};

3. Create a dictionary store final path
NSString *dictionpath = [documentPath2 stringbyappendingpathcomponent:@ "Leishen.plist"];
4. Writing a dictionary to a file
[Dictionarypath Writetofile:dictionpath Atomically:yes];
NSLog (@ "Dictionpath =%@", Dictionpath);

A local dictionary will be present to take out

Nsdictionary *newdictionary = [Nsdictionary Dictionarywithcontentsoffile:dictionpath];
NSLog (@ "newdictionary =%@", newdictionary);

#pragma mark-store data of type NSData to local, (take picture for example)
Two common ways to initialize an image
1. Use imagenamed: First read the time, first put this picture in the cache, the next time you use the same name picture of the time to read directly from the cache; advantages: Convenient and fast, only the first use of the time is slightly slower, the next in use is slightly faster; Disadvantages: If you use it only once in the current project, you will waste memory
UIImage *image = [UIImage imagenamed:@ "1.jpg"];

2. Use Initwithcontentsoffile to initialize the picture, each time according to the path to read, do not occupy memory, if the picture is used only once in the current project, you should choose this method

UIImage *image = [[UIImage alloc] initwithcontentsoffile:@ "/users/zhaoce/documents/Courseware Practice/ui Advanced/first Section/uisenior_ 1 Simple data storage/uisenior_1 simple data storage/1.jpg "];


/**
123.png
123@2x.png
123@3x.png
Picture adaptation related content
*/
Converts an object of type image to a nsdata type of data for storage
Use UIImageJPEGRepresentation to convert a picture into a nsdata type
First parameter: The Image object to convert
Second parameter: A value that represents picture compression
The iphone will be larger than 2M images, will automatically rotate 90 degrees, compression processing, so will eventually save the image in JPEG format

NSData *imagedata = uiimagejpegrepresentation (image, 1);
Find path to store
NSString *documentpath4 = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) OBJECTATINDEX:0];
Final path
NSString *imagepath = [DocumentPath4 stringbyappendingstring:@ "/123.jpeg"];

Write file
[ImageData Writetofile:imagepath Atomically:yes];
NSLog (@ "ImagePath =%@", ImagePath);

Reading NSData Types of data
Requirement: NSData type of data is read out, converted to UIImage type and displayed on ImageView
NSData *newdata = [NSData Datawithcontentsoffile:imagepath];
UIImage *showimage = [[UIImage alloc] initwithdata:newdata];
Uiimageview *showimageview = [[Uiimageview alloc] initwithimage:showimage];
[Self.view Addsubview:showimageview];

NSString *cachespath = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) OBJECTATINDEX:0];
NSString *string = @ "I love You";
//
NSString *stringpath = [Cachespath stringbyappendingpathcomponent:@ "Leikun.txt"];
[String Writetofile:stringpath atomically:yes encoding:nsutf8stringencoding Error:nil];
NSLog (@ "Stringpath =%@", Stringpath);
NSString *newstring = [NSString stringwithcontentsoffile:stringpath encoding:nsutf8stringencoding Error:nil];
NSLog (@ "newstring =%@", newstring);

NSString *cachespath = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) OBJECTATINDEX:0];
Nsarray *array1 = @[@ "he", @ "Thor", @ "lei June"];
NSString *arraypath1 = [Cachespath stringbyappendingpathcomponent:@ "Leikun.plist"];
[Array1 writetofile:arraypath1 Atomically:yes];
//
NSLog (@ "arrayPath1 =%@", arrayPath1);
//
Nsarray *newarray1 = [Nsarray arraywithcontentsoffile:arraypath1];
NSLog (@ "newArray1 =%@", newArray1);

NSString *cachespath = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) objectAtIndex : 0];
Nsdictionary *dic = @{
@ "name": @ "Love",
@ "Gender": @ "You",
@ "Age": @100

};

NSString *dicpath = [Cachespath stringbyappendingpathcomponent:@ "Nvshen.plist"];

[DiC Writetofile:dicpath Atomically:yes];

NSLog (@ "Dicpath =%@", Dicpath);

Nsdictionary *newdic = [Nsdictionary Dictionarywithcontentsoffile:dicpath];
NSLog (@ "newdic =%@", newdic);




UIImage *image1 = [UIImage imagenamed:@ "2.jpg"];

NSData *imagedata = UIImageJPEGRepresentation (image1, 1);

NSString *cachespath1 = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) objectAtIndex : 0];

NSString *imagepath1 = [cachesPath1 stringbyappendingstring:@ "/234.jpeg"];
[ImageData writetofile:imagepath1 Atomically:yes];

NSLog (@ "imagePath1 =%@", imagePath1);

NSData *newdata1 = [NSData datawithcontentsoffile:imagepath1];
UIImage *showimage1 = [[UIImage alloc] initwithdata:newdata1];
Uiimageview *showimageview1 = [[Uiimageview alloc] initwithimage:showimage1];

[Self.view Addsubview:showimageview1];

}

5. Localization of complex objects

3. Declaring a property in the. h file of the model object

Name
@property (nonatomic, copy) NSString *name;

Gender
@property (nonatomic, copy) NSString *gender;

Age
@property (nonatomic, assign) Nsinteger age;

Semantic setting some content; (15 kinds)

4. Implementing methods in the. m file of the model object

Archive
Archive all the attributes
-(void) Encodewithcoder: (Nscoder *) Acoder
{
[Acoder encodeObject:self.name forkey:@ "name"];
[Acoder encodeObject:self.gender forkey:@ "gender"];
[Acoder encodeInteger:self.age forkey:@ "age"];


}

Solution (Reverse archive)
-(Instancetype) Initwithcoder: (Nscoder *) Adecoder
{
self = [super init];
if (self) {
Self.name = [Adecoder decodeobjectforkey:@ "name"];
Self.gender = [Adecoder decodeobjectforkey:@ "gender"];
Self.age = [Adecoder decodeintegerforkey:@ "age"];
}
return self;
}

5. File and archive in Viewcontroller

How to store objects of a person type locally, that is, for the localization of complex objects, this object must adhere to the Nscoding protocol and implement two methods in the Protocol
#pragma mark-Localization of complex objects
#pragma mark-Archive
1. Find the directory of Documents folder
NSString *documentpath = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) OBJECTATINDEX:0];
2. Create a Person object
Person *person = [[Person alloc] init];
Person.name = @ "Mbboy";
Person.gender = @ "male";
Person.age = 18;
3. Archive this complex object

3.1: Create initialization nsmutabledata, for creating archive tools
Nsmutabledata *data = [Nsmutabledata data];

NSLog (@ "======data =%@======", data);

3.2: Create an archive tool
Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data];
3.3: Archive the Person object to be archived
[Archiver encodeobject:person forkey:@ "person"];
3.4: End Archive
[Archiver finishencoding];

NSLog (@ "======data =%@======", data);

4. Store archived content on-premises
NSString *personpath = [documentpath stringbyappendingpathcomponent:@ "Person.plist"];
[Data Writetofile:personpath Atomically:yes];
NSLog (@ "Personpath =%@", Personpath);

#pragma mark-de-document
1. Find out the data that will be solved
NSData *resultdata = [NSData Datawithcontentsoffile:personpath];
NSLog (@ "resultdata =%@", resultdata);

2. Create a profile tool
Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:resultdata];
3. Document the Person object [to use object to receive]
Person *newperson = [unarchiver decodeobjectforkey:@ ' person '];
4. End the solution
[Unarchiver finishdecoding];
NSLog (@ "name =%@, gender =%@, age =%ld", newperson.name,newperson.gender,newperson.age);
Step Memory Good
Write directly to Local: data is saved for the whole



}

The sandbox mechanism of data localization

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.