NSString
----------------of instantiation methods
NSString *str = [[NSString alloc] init];
NSString *STR = [[[NSString alloc] init]autorelease];
Note: There are ways to instantiate and initialize your own in NSString, for example:
NSString *str1 = [NSString stringwithcstring: "newstring" enconding:nsaciistringencoding];
NSString *STR2 = [NSString alloc]initwithcstring: "New String" enconding:nsaciistringencoding];
STR1 and str2 Two objects are the same.
The character encoding commonly used in--nsstringencoding----------------
Nsasciistringencoding
Nsutf8stringencoding
Nsunicodestringencoding
--nsstring Creating an instance----------------
A method with the "@" symbol can only define NSString instances that contain English and numerals, for example:
NSString *str = "Hello money~";
--Generate NSString methods containing Chinese-------------
This method automatically frees memory
+ (ID) stringwithcstring: (const char*) cstringencoding: (nsstringencoding) encoding;
Initialize after Alloc
-(ID) initwithcstring: (const char*) cstringencoding: (nsstringencoding) encoding;
For example:
NSString *string = [nsstringstringwithcstring: "Hello" encoding:nsutf8stringencoding];
NSString *string = [[NSString alloc]initwithcstring: "Hello" encoding:nsutf8stringencoding];
--use format to create strings-------------
+ (ID) stringWithFormat: (NSString *) format ...
-(ID) Initwithformat: (NSString *) format ...
For example:
Nsstring*str = "Hello";
nsstring*string = [NSString stringwithformat:@ "%@ World", str];
NSLog (string); Results: HelloWorld
Can be used to describe the full path,
--Commonly used substitutions--------------
%@ NSString Instances
%d,%d,%i integer
%u,%u unsigned integer
%x displays unsigned integers in hexadecimal lowercase letters
%x displays unsigned integers in hexadecimal capitals
%f Decimal
%c character
%s C language String
Percent display% character itself
--------------------------
Nsrange
Definition of--nsrange
typedef struct _NSRANGE
{
unsigned int location;
unsigned int length;
}nsrange;
Nsmakerange function
-This function returns a Nsrange object in particular.
Nsmakeranger (unsigned int location,unsigned int length);
For example:
Nsrange range = Nsmakeranger (0,5);
NSLog (@ "location is%d,length is%d", range.location,range.length);
---------------------------
Calculating string Lengths
-(unsigned int) length;
---------------------------
String joins, insertions and deletions
1. Connection
-(NSString *) stringbyappendingstring: (NSString *) string;
-(NSString *) Stringbyappendingformat: (NSString *) format ...;
For example:
NSString *str1 [email protected] "Hello";
NSString *str2 [email protected] "world";
NSString *STR3 = [STR1STRINGBYAPPENDINGSTRING:STR2];
NSString *STR4 = [str2stringbyappendingformat:@ "%d...%d", 10,20];
STR4 to World 10...20
-----------------
Generation of Nsmutablestring
NSString + (ID) string; Generate an instance of an empty string
+ (ID) stringwithstring: (NSString *) string; With automatic memory release
-(ID) initwithstring: (nsstring*) string;
For example:
nsmutablestring *string =[nsmutablestring stringwithstring:@ "Hello"];
2. Append string
Nsmutablestring
+ (void) appendString: (nsstring*) string;
-(void) AppendFormat: (nsstring*) format ...;
For example:
nsmutablestring string = [nsmutablestringstring];
[stringappendstring:@ "Hello"];
[stringappendstring:@ "Money"];
[String appendstring:@ "Andworld"];
3. Inserting a string
Nsmutablestring
+ (void) insertstring: (NSString *) Stringatindex: (unsigned) index;
Insert a string from the index position
For example:
nsmutablestring *string =[nsmutablestring stringwithstring:@ "Mac X"];
[String insertstring:@ "OS" atindex:4];
String--Mac OS X
4. Delete a string
Nsmutablestring
+ (void) Deletecharactersinrange: (nsrange) range;
For example:
nsmutablestring *string =[nsmutablestring stringwithstring:@ "Mac os"];
[Stringdeletecharactersinrange:nsmakeranger (0,1)];
NSLog (string);
String-->ac os;
5. String comparison
NSString
-(BOOL) isequaltostring: (nsstring*) string;
6. Compare front and rear strings
NSString
-(BOOL) Hasprefix: (nsstring*) string;
-(BOOL) Hassuffix: (nsstring*) string;
For example:
NSString *str1 = @ "MacOS";
NSString *str2 = @ "MacPro";
BOOL Flag;
flag = [str1hasprefix:@ "Mac"]; YES
flag = [str2hassuffix:@ "OS"]; NO
7. String retrieval
NSString
Returns the range if found, otherwise Nsrange's location entry is set to Nsnotfound
-(Nsrange) rangeofstring: (nsstring*) subString;
-(Nsrange) rangeofstring: (nsstring*) subString option: (unsigned) mask;
-(Nsrange) rangeofstring: (nsstring*) subString option: (unsigned) Mask range: (nsrange) range;
-----mask List of common options
Nscaseinsensitivesearch does not distinguish between uppercase and lowercase letters
Nsliteralsearch a byte-unit comparison of strings, which generally improves retrieval speed
Nsbackwardssearch starting from the end of the range
Nsanchoredsearch retrieves only the front part of the development scope. Ignore search characters in the middle of a string
For example:
NSString *string = @ "HelloWorld";
Nsrange range = [stringrangeofstring:@ "he"];
if (range.location! = nsnotfound)
{
NSLog (@ "location=%d,length=%d", range.location,range.length);
}
8. Intercepting strings
NSString
-(nsstring*) Substringtoindex: (unsigned) index; The string that returns the string beginning to the index bit does not contain an index bit
-(nsstring*) Substringfromindex: (unsigned) index; String that returns the index bit to the end of the string containing the indexed bit
-(nsstring*) Substringwithrange: (nsrange) range; Returns a string containing an index bit within a range in a string
For example:
NSString *string = [Stringsubstringwithrange:nsmakerange (5,2)];
9. Read the text file
NSString
+ (ID) stringwithcontentsoffile: (NSString *) path usedencoding: (nsstringencoding*) ENC error: (NSERROR *) error//Automatically free memory
-(ID) Initwithcontentsoffile: (nsstring*) path encoding: (nsstringencoding) ENC error: (NSERROR *) error
+dictionarywithcontentsoffile
+dictionarywithcontentsofurl
For example:
NSString *string = [nsstringstringwithcontentsoffile:@ "/user/test/yw.txt" encoding:nsutf8stringencoding error:& ERROR];
if (string) {}
10. Output text File
NSString
-(BOOL) WriteToFile: (NSString *) pathatomically: (BOOL) useauxiliaryfile encoding: (nsstringencoding) ENC error: ( nserror**) Error
Parameter atomically temporarily saves the file to the secondary file
Extension path
NSString *path [email protected] "~/nsdata.txt";
NSString *absolutepath = [Pathstringbyexpandingtildeinpath];
NSLog (@ "absolutepath:%@", Absolutepath);
NSLog (@ "path:%@", [Absolutepathstringbyabbreviatingwithtildeinpath]);
File name extension
NSString *path [email protected] "~/nsdata.txt";
NSLog (@ "extension:%@", [pathpathextension]);
Before initializing a class: testviewcontroller*viewcontroller=[[testviewcontrolleralloc]initwithnibname:@ "TestViewController" Bundle:[nsbundlemainbundle]]; not very clear: [NSBundle mainbundle] means. Later, after reviewing the information, I knew its function, as follows:
A bundle is a directory that contains the resources that the program will use. These resources include like, sound, compiled code, NIB files (the user will also refer to bundles as plug-in). The corresponding BUNDLE,COCOA provides class NSBundle. Our program is a bundle. In the Finder, an application looks no different from other files. But it's actually a directory that contains nib files, compiled code, and other resources. We call this directory the program's main bundle.
Get the program's main bundle by using the following method
NSBundle *mybundle = [NSBundle mainbundle];
In general, we use this method to get bundles. If you need resources for another directory, you can specify a path to get the bundle
NSBundle *goodbundle;
Goodbundle = [nsbundlebundlewithpath:@ "~/.myapp/good.bundle"];
Once we have the NSBundle object, we have access to the resources in it.
A nsbundle bundle, which is a specific type of file in which the content follows a specific structure.
One of the main functions of nsbundle is to obtain resources in the resource folder.
When using [nsdatadatawithcontentoffile:@ "foo"] in programming, it is always impossible to read the correct file contents. It is possible to use [NSData datawithcontentoffile:[[nsbundle mainbundle]pathforresource:@ "foo" oftype:@ ""].
Because when using relative path, in fact his relative current directory is not the directory that the program runs, but "/". Only the path generated using [Nsbundlemainbundle] is the true path to the file.
Here's a note: instead of using any relative path directly in future development, use the absolute path after the calculation.
I. Getting pictures
1. NSString *path = [[Nsbuddle mainbuddle]pathforresource:@ "resourcename" [email protected] "resourcetype"];
UIImage *image =[[uiimage Imagewithcontentsoffile:path];
2. UIImage *image = [uiimageimagenamed:@ "ImageName"];
Two. Get the plist file
Nsarray *array =[[nsarray alloc]initwithcontentsoffile:[[nsbundle mainbundle]pathforresource:@ "name" ofType:@ "plist "]];
nsdictionary*dict=[arrayobjectatindex:index];//converting the contents of the plist file into a dictionary
Nsfilemanager,defaultmanager () returns a single instance of a file manager (unsafe under multithreading). Init (), you should use Init () as much as possible in multithreaded programming.
Proxy methods:-filemanager:shouldremoveitematpath and-filemanager:shouldremoveitematurl are called before the removal operation.
-removeitematpath:error: Deletes the file, connection, directory (and all subdirectories, files) located at the specified path.
-removeitematurl:error: Ibid.
-contentofdirectoryatpath: Finds all sub-paths and files at the given path. The return value is an array that contains the NSString object. The lookup is made only in the current directory and does not go to the next level directory.
-subpathsatpath: Finds all sub-paths under the given path. Deep lookup, not limited to the current layer, will also look for the contents of the package.
-fileexistsatpath: Determine if the file is located under a path.
-isreadablefileatpath: Querying the readability of a file
-iswritablefileatpath: Writable
-isexecutablefileatpath: Querying the executable of a file
-isdeletablefileatpath: Removable
3-nsstring path function
-pathwithcomponent: The parameter is a stack of components, and the path returned is a string of paths that are connected by these elements, separated by the neighboring components.
-pathcomponents: Returns an array containing the components in the path.
-filesystemrepresentation: Return C string
-isabsolutepath: Determine if the absolute path
-pathextension: Returns the file extension without returning an empty string
-stringbyappendingpathcomponents: Adds a component to an existing path. Slash/will be automatically added
-stringbyappendingpathextension: Add a file extension to an existing path
-stringbydeletinglastpathcomponent: Remove the last path component
-stringbydeletingpathextension: Remove Path extension
-stringbyappendingpaths: parameter is an array that adds a string object in the array to the source string once as a path.
Example:
NSString *homepath = Nshomedirectory ();
NSString *docpath = [homepathstringbyappendingformat:@ "/documents"];
1-Audio
[1] Music is often stored in the ipod music library (note location), can be read through the media selector (medium picker) or media query, and then played mpmusicplayercontroller with the music player.
Mpmusicplayercontroller *musicplayer =[mpmusicplayercontroller Applicationmusicplayer];
[Musicplayer setshuflemode:mpmusicshufflemodesongs];
[Musicplayer Setrepeatmode:mpmusicrepeatmodeall];
[Musicplayer setqueuewithquery:[mpmediaquery songsquery];
[Musicplayer play];
Applicationmusicplayer returns the player that plays music in your app. It does not affect the ipod player, nor does it retrieve information from the ipod player.
Ipodmusicplayer returns an ipod player, and after you launch the app, all settings will affect the ipod player on your device.
Once you have a music player, you need to set up a play queue for it. Can use Setqueuewithquery: Put method, through the media query Mpmediaquery to set the play queue, you can also use Setqueuewithitemcollection: Method, Set up the play queue via mpmdiaitemcollection.
The repeating mode Repeatmode can be set to not repeat, repeat the current track, or the entire playlist, and shuffle play Shufflemode can be set to not shuffle, shuffle the tracks or shuffle the album, the volume volume is the same as the audio player.
Skiptonextitem jumps to the next song, Skiptopreviousitem jumps to the previous song, Skiptobegin jumps to the first song.
The corresponding macro starts with Mpmusic.
[2] Use the system sound service to play a short sound (30 seconds or less), and vibrate:
Audioservicesplaysystemsound (ksystemsoundid_vibrate);
Play the specified sound:
Nsurl *fileurl = [Nsurl FileURLWithPath:pathisDirectory:NO];
Create a sound ID
Systemsoundid Soundid;
Audioservicecreatesystemsoundid ((cfurlref) fileurl,&soundid);
Play sound
Audioservicesplaysystemsound (Soundid);
[3] Audio player
No time limit
Nsurl *fileurl = [Nsurl FileURLWithPath:pathisDirectory:NO];
Initializing the audio player with a URL-not playing music in the ipod gallery
avaudioplayer* player = [Avaudioplayeralloc] Initwithcontentsofurl:fileurl Error:no];
Ready to play
[Player Preparetoplay];
Set up Proxy
[Player Setdelegate:self];
Method: Play, pause, stop. You can query whether the player is playing through the playing property, you can modify and query the player's playback gain (from 0.0 to 1.0) through the volume property, and you can query the player's other settings through the setting property.
Duration represents the length of time the audio is, and CurrentTime indicates the current time to play. After playback, you can use the Proxy method audioplayerdidfinishplaying: To process post-playback settings.
Video
Video playback can be played in a Web Page view (UIWebView) for embedded playback (YouTube video) or in a movie player (MPMoviePlayerController).
[1] Movie player
MPMoviePlayerController *player = [Mpmovieplayercontrolleralloc]initwithcontenturl:url];
Set the size of the player and add it to the view
[Player.view Setframe:rectframe];
[Self.view AddSubView:player.view];
The background view of the player is Backgroundview.
fullscreen [player Setfullscreen:yes Animated:yes];
Play another movie [player Setcontenturl:newurl];
[PlayerrequestThumbnailImagesAtTimes:arrayTimestimeOption:MPMovieTimeOptionNearestKeyFrame]; Indicates that the player does not intercept previews at the time you specify, but rather looks for the best-performing frames in a few frames near the absolute time as previews.
SCALINGMODE Specifies the zoom mode of the movie.
The initialplaybacktime is used to control when the video starts playing, in seconds.
If the video source is on the network, then the server-side mimetype needs to be set correctly
The first uses the For loop plus the Count method to traverse
?
1 2 3 4 5 |
int i = 0; for (i = 0; i < [array count]; i++) { [Array objectatindex:i] } |
The second uses the for in method to traverse
?
1 2 3 4 |
For (NSString *str in array) { Operation } |
The third way to iterate using enumerations
?
1 2 3 4 5 6 7 |
Nsenumerator *enumer; Emumer = [array objectenumerator]; NSString *str; while (str = [Enumer nextobject]) { Operation } |
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Foundation Framework and file operations