[IOS learning basics] File-related, ios learning basics

Source: Internet
Author: User

[IOS learning basics] File-related, ios learning basics

 

I. SandBox)

1. Sandbox Mechanism

1> each application has its own storage space, I .e., sandbox.
2> applications can only access their sandbox but cannot access other regions.
3> If the application needs to perform file operations, the files must be stored in the sandbox, especially the database files, which can be accessed during operations on the computer, but if you want to install it on a real machine, you must copy the database file to the sandbox.

2. Sandbox directory structure

1> Documents: files created in applications, such as databases, can be stored here. This directory will be included during iTunes backup and recovery.
2> tmp: stores temporary files sent in time. iTunes does not back up and restore the directory. files in this directory may be deleted after the application exits.
3> Library/Caches: stores cached files. iTunes does not back up this directory, and files under this directory are not deleted after the application exits.
4> Library/Preferences: application Preferences. NSUserDefault, which we often use, is stored in a Plist file under this directory. iTnues will also synchronize this file.

3. Several Parameters

NSSearchPathForDirectoriesInDomains (NSSearchPathDirectory, NSSearchPathDomainMask domainMask, BOOL expandTilde); directory
The enum value of the NSSearchPathDirectory type indicates the directory name (NSDocumentDirectory, NSCachesDirectory) to be searched.

DomainMask
NSSearchPathDomainMask type enum value, specifying the search range. Here, NSUserDomainMask indicates that the search range is limited to the sandbox directory of the current application. It can also be written as NSLocalDomainMask (/Library) and NSNetworkDomainMask (/Network.

ExpandTilde
BOOL value, indicating whether to expand the Tilde ~. We know that in iOS ~ The full write format is/User/userName. If the value is YES, it indicates that the full write format is used. If it is NO, it indicates that it is directly written as "~".

4. Obtain the sandbox path

# Pragma mark sandbox main path-(NSString *) homePath
{Return NSHomeDirectory () ;}# pragma mark user application data path + (NSString *) getDocuments
{NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString * path = [paths objectAtIndex: 0]; return path ;}# pragma mark cache data path + (NSString *) getCache {NSArray * paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES); return paths [0] ;}# pragma mark temporary file path + (NSString *) getTemp {return NSTemporaryDirectory () ;}# pragma mark Library PATH + (NSString *) getLibrary {NSArray * paths = NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES ); NSString * path = [paths objectAtIndex: 0]; return path ;}

In development, the sandbox path is usually printed. In addition to NSLog output, this can also be done (note that breakpoint debugging is required)
Ii. NSBundle

1. NSBundle * mainBundle = [NSBundle mainBundle];

Bundle is a directory that contains the resources used by the program. these resources contain images, sounds, compiled code, and nib files (bundle is also called plug-in ). corresponding bundle. cocoa provides the NSBundle class. our program is a bundle. in the Finder, an application looks no different from other files. but it is actually a directory that contains nib files, compiled code, and other resources. we call this directory the main bundle of the program.

NSLog (@ "Get app package path: % @", mainBundle. bundlePath); NSLog (@ "Get app resource directory path: % @", mainBundle. resourcePath); NSLog (@ "Application ID bundle Identifier: % @", mainBundle. bundleIdentifier); NSLog (@ "info. plist information and others: % @ ", mainBundle. infoDictionary );

Tip: For the problem of printing dictionary or array Chinese garbled characters, please search for NSDitionary/NSArray + Log classification or rewrite their-(NSString *) descriptionWithLocale :( id) locale method.

2. Use of Bundle

1> Create a Bundle: Since Bundle is a directory, you can create a folder, put the required resource material in it, and rename the folder "file name. bundle, and a prompt box (such as) will pop up later. Click "add ".


2> Read your Bundle resources (using Baidu SDK as an example)
The IphoneMapSdkDemo sample program of Baidu map contains an image resource package named "mapapi. bundle ".


In the "AnnotationDemoViewController. m" file of its demo, several macros are defined.
// Resource package file name # define MYBUNDLE_NAME @ "mapapi. bundle "// concatenate mapapi. bundle resource package path # define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME] // obtain mapapi. bundle resource package # define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
// Load a file specified in the Resource Package
[[NSBundle mainBundle] pathForResource: @ "XXX.png (file name to be retrieved)" ofType: nil inDirectory: @ "mapapi. bundle"];
// Load the xib File
NSArray * views = [[NSBundle mainBundle] loadNibNamed: @ "MyView" owner: nil options: nil];
  Iii. NSFileManager file management class

1. NSFileManager is mainly used for basic operations on directories and files, and is a singleton object (Singleton mode: A design mode, that is, a class always has only one class object ), NSFileManager * fm = [NSFileManager defamanager manager] during use.

2. macro definition quick implementation of Singleton (I saw it on the Internet a few days ago and thought it was good. Record it)

1> Create a "Singleton. h" file and paste the following code into it:

// .h#define singleton_interface(class) + (instancetype)shared##class;// .m#define singleton_implementation(class) \static class *_instance; \\+ (id)allocWithZone:(struct _NSZone *)zone \{ \    static dispatch_once_t onceToken; \    dispatch_once(&onceToken, ^{ \        _instance = [super allocWithZone:zone]; \    }); \\    return _instance; \} \\+ (instancetype)shared##class \{ \    if (_instance == nil) { \        _instance = [[class alloc] init]; \    } \\    return _instance; \}

2> create a new class, which is written as code in the. h file and. m file respectively,

 

3> Use: SingerTest * test = [SingerTest sharedSingerTest];

 

3. method collection

Common Path tool Functions

NSString * NSUserName (void );

Returns the username of the current logon.

NSString * NSFullUserName (void );

Returns the complete user name of the current user.

NSString * NSHomeDirectory (void );

Returns the path of the current home directory (commonly used)

NSString * _ nullable NSHomeDirectoryForUser (NSString * _ nullable userName );

Returns the Home Directory of the specified user name.

NSString * NSTemporaryDirectory (void );

Returns the directory path used to create a temporary folder.

NSString * NSOpenStepRootDirectory (void );

Returns the system root directory of the current user.

 

 

File/directory Problems

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

Determine whether a file or folder exists in the path

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

Determine whether the path is a file
-(BOOL) createDirectoryAtPath :( NSString *) path withIntermediateDirectories :( BOOL) createIntermediates attributes :( nullable NSDictionary <NSString *, id> *) attributes error :( NSError **) error

Create folder

Parameters:

1-Folder path.

2-YES: if the file does not exist, it is created; NO, the folder is not created.

3-folder attributes, which can be read and written. Generally, nil is passed.

4-error message.

-(BOOL) removeItemAtPath :( NSString *) path error :( NSError **) error Remove files/folders
-(BOOL) copyItemAtPath :( NSString *) srcPath toPath :( NSString *) dstPath error :( NSError **) error Copy files/folders
-(BOOL) moveItemAtPath :( NSString *) srcPath toPath :( NSString *) dstPath error :( NSError **) error Move files/folders

-(BOOL) createFileAtPath :( NSString *) path contents :( nullable NSData *) data attributes :( nullable NSDictionary <NSString *, id> *) att

Create a file

Parameters:

1-file path (last spliced file name)

2-file data to be created

3-attributes

 

-(BOOL) contentsEqualAtPath :( NSString *) path1 andPath :( NSString *) path2;

Compare whether the files in two paths are the same

 

 

 

 

 

 

Common NSPathutilities path processing methods (extensions)

-(Nullable NSArray <NSString *> *) contentsOfDirectoryAtPath :( NSString *) path error :( NSError **) error NS_AVAILABLE (10_5, 2_0 );

Traverse the files in the path directory and return an array

-(Nullable NSData *) contentsAtPath :( NSString *) path;

Obtain file data in path

-(Nullable NSArray <NSString *> *) subpathsAtPath :( NSString *) path;

Recursively retrieve the sub-directory list

+ (NSString *) pathWithComponents :( NSArray <NSString *> *) components;

Create a path using an array

PathComponents

An array

LastPathComponent

Last part of the path

PathExtension

File Extension

-(NSString *) stringBy + <Appending/Deleting> + Path + <Component/Extension> :( NSString *) str;

<SPLICE/delete> + <path/suffix> name at the end

 

 

 

 

  4. NSFileHandle File handle class (equivalent to File in C)

1. It is used for I/0 operations on files. It is equivalent to a file operation handle and can control files more effectively, similar to file management in C language.

2. Use NSFileHandle

1> open a file and obtain an NSFileHandle object (Note: If this file does not exist, you cannot obtain the NSFileHandle object using the following methods)

// Open a file and prepare to read NSFileHandle * fp = [NSFileHandle fileHandleForReadingAtPath: path]; // open a file and prepare to write it into NSFileHandle * fp = [NSFileHandle fileHandleForWritingAtPath: path]; // open a file and prepare to update (read/write) NSFileHandle * fp = [NSFileHandle fileHandleForUpdatingAtPath: path];

2> perform the I/0 operation on the opened file

// Write a file
[Data WriteToFile: path atomically: YES]

3> close the file (note: in C language, all operations will close the file after it is completed. You must close the file here to ensure file security)

// Close the file [fp closeFile];

3. An important concept of NSFileHandle: handle (the following process helps you understand the role of the handle)-it will be used in subsequent NSURLConnection writes.

Mark the file so that the user can store the file from this mark the next time the file is written. The seekToEndOfFile method moves the handle to the end of the file after each storage.

 

5. NSProcessInfo (learn more)
-(NSArray *) arguments // return the parameter-(int) processIdentifier of the current process as an array // return the process identifier (process id ), used to identify each running process-(NSString *) processName // return the name of the currently executing process-(NSString *) globallyUniqueString // each time this method is called, different single-value strings are returned. You can use this string to generate a temporary Single-value File Name-(NSString *) hostname // return the host system name-(NSUInteger) operatingSystem // return the number of the Operating System
-(NSString *) operatingSystemName // return the name of the Operating System-(NSString *) operatingSystemVersionString // return the current version of the operating system
-(Void) setProcessName :( NSString *) name // set the name of the current process to name. This method should be used with caution. There should be some assumptions about the process name (such as the user's default settings)

 

 

    

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.