Document directory
- Write log
- Image Display
- Application border size
- Web View
- Display the network activation status icon
- Animation: A group of images
- Animation: Move an object
- Nsstring and INT type conversion
- Zheng ze expression (RegEx)
- Items that can be dragged, items
- Vibrate and sound playback
- Thread
- Read the crash log file
- Test
- Access properties/methods in other classes
- Create random number
- Timer
- Application Analysis
- Time
- Warning window
- Plist File
- Info button
- Find subviews (detecting subviews)
- Manual documentation
Write logs in xcode. Click RUN> console to view nslog records.
Nslog (@ "log: % @", mystring );
Nslog (@ "log: % F", myfloat );
Nslog (@ "log: % I", Myint); image display does not require UI resource binding, and images are displayed anywhere on the screen. The following code can be used in any view.
Cgrect myimagerect = cgrectmake (0.0f, 0.0f, 3200000f, 109.0f );
Uiimageview * myimage = [[uiimageview alloc] initwithframe: myimagerect];
[Myimage setimage: [uiimage imagenamed: @ "myimage.png"];
Myimage. opaque = yes; // explicitly opaque for performance
[Self. View addsubview: myimage];
[Myimage release]; we should use"
Bounds"To obtain the application border. Not used"
Applicationframe". "
Applicationframe"It also contains a 20-pixel status bar. Unless we need the extra 20-pixel status bar. Call the Web viewuiwebview class.
Cgrect webframe = cgrectmake (0.0, 0.0, 320.0, 460.0 );
Uiwebview * webview = [[uiwebview alloc] initwithframe: webframe];
[Webview setbackgroundcolor: [uicolor whitecolor];
Nsstring * urladdress = @ "http://www.google.com ";
Nsurl * url = [nsurl urlwithstring: urladdress];
Nsurlrequest * requestobj = [nsurlrequest requestwithurl: url];
[Webview loadrequest: requestobj];
[Self addsubview: webview];
[Webview release]; the Network activation status icon is displayed in the upper-left corner of the iPhone status bar. If it is rotated, the network is in use.
Uiapplication * APP = [uiapplication sharedapplication];
App. networkactivityindicatorvisible = yes; // to stop it, set this to noanimation: displays a group of images consecutively.
Nsarray * myimages = [nsarray arraywithobjects:
[Uiimage imagenamed: @ "myimage1.png"],
[Uiimage imagenamed: @ "myimage2.png"],
[Uiimage imagenamed: @ "myimage3.png"],
[Uiimage imagenamed: @ "myimage4.gif"],
Nil];
Uiimageview * myanimatedview = [uiimageview alloc];
[Myanimatedview initwithframe: [self bounds];
Myanimatedview. animationimages = myimages;
Myanimatedview. animationduration = 0.25; // seconds
Myanimatedview. animationrepeatcount = 0; // 0 = loops forever
[Myanimatedview startanimating];
[Self addsubview: myanimatedview];
[Myanimatedview release]; Animation: moves an object so that an object is displayed as a moving track on the screen. Note: This animation is called "fire and forget ". That is to say, programmers cannot obtain any information (such as the current location) in the animation process ). If you need this information, you need to adjust the X & Y coordinates as necessary through the animate and timer.
Cabasicanimation * theanimation;
Theanimation = [cabasicanimation animationwithkeypath: @ "transform. Translation. X"];
Theanimation. Duration = 1;
Theanimation. repeatcount = 2;
Theanimation. autoreverses = yes;
Theanimation. fromvalue = [nsnumber numberwithfloat: 0];
Theanimation. tovalue = [nsnumber numberwithfloat:-60];
[View. layer addanimation: theanimation forkey: @ "animatelayer"]; nsstring and INT conversion the following example shows an integer value displayed by a text label.
Currentscorelabel. Text = [nsstring stringwithformat: @ "% d", currentscore]; the current framework of the regular expression (RegEx) does not support RegEx. Developers cannot use the RegEx including nspredicate on the iPhone. But nspredicate can be used on the simulator, that is, nspredicate cannot be supported on the real machine. The following figure shows how to create a drag-and-drop image object:
1. Create a new class to inherit uiimageview.
@ Interface mydraggableimage: uiimageview {
}
2. Add two methods when implementing the new class:
-(Void) touchesbegan :( nsset *) touches withevent :( uievent *) event {
// Retrieve the touch point
Cgpoint Pt = [[touches anyobject] locationinview: Self];
Startlocation = pt;
[[Self superview] bringsubviewtofront: Self];
}
-(Void) touchesmoved :( nsset *) touches withevent :( uievent *) event {
// Move relative to the original touch point
Cgpoint Pt = [[touches anyobject] locationinview: Self];
Cgrect frame = [self frame];
Frame. Origin. x + = pt. X-startlocation. X;
Frame. Origin. Y + = pt. Y-startlocation. Y;
[Self setframe: frame];
}
3. Create another image and add it to the newly created uiimageview.
Dragger = [[mydraggableimage alloc] initwithframe: mydragrect];
[Dragger setimage: [uiimage imagenamed: @ "myimage.png"];
[Dragger setuserinteractionenabled: Yes]; The following describes how to shake a mobile phone during vibration and sound playback (Note: vibration is not supported in simulator, but can be supported on a real machine .)
Audioservicesplaysystemsound (ksystemsoundid_vibrate );
Sound will work in the simulator, however some sound (such as looped) has been reported as not working in simulator or even altogether depending on the audio format. note there are specific filetypes that must be used (.wav in this example ).
Systemsoundid pmph;
Id sndpath = [[nsbundle mainbundle]
Pathforresource: @ "mysound"
Oftype: @ "WAV"
Indirectory: @ "/"];
Cfurlref baseurl = (cfurlref) [[nsurl alloc] initfileurlwithpath: sndpath];
Audioservicescreatesystemsoundid (baseurl, & pmph );
Audioservicesplaysystemsound (pmph );
[Baseurl release]; thread 1. Create a New thread:
[Nsthread detachnewthreadselector: @ selector (
Mymethod)
Totarget: Self
Withobject: Nil];
2. method called to create a thread:
-(Void)
Mymethod{
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
*** Code that shoshould be run in the new thread goes here ***
[Pool release];
}
If we need to call the main thread's method function in the thread, we can usePerformselecdomainmainthreadTo achieve:
[Self defined mselecw.mainthread: @ selector (
Mymethod)
Withobject: Nil
Waituntildone: false]; if it is unfortunate to read the crash log file that some of our code has caused crash, you can read this article and it should be useful: navigate here Test 1. in the simulator, click hardware> Simulate Memory warning to test. then every page of our entire program can support this function.
2. Be sure to test your app in airplane mode. Access properties/methods in other classesone way to do this is via the appdelegate:
Myappdelegate * appdelegate
= (Myappdelegate *) [[uiapplication sharedapplication] Delegate];
[[Appdelegate rootviewcontroller] flipsideviewcontroller] mymethod]; create a random number call
Arc4random ()To create a random number. You can also use
Random ()But you must manually set the seed to bind with the system clock. In this way, the values obtained each time are different. Therefore, arc4random () is better. The timer under the timer will be called once every minute
Mymethod.
[Nst1_scheduledtimerwithtimeinterval: 1
Target: Self
Selector: @ selector (
Mymethod)
Userinfo: Nil
Repeats: Yes];
When we need to provide the timer processing functionMymethodWhat should I do when passing parameters? Use the "userinfo" attribute.
1. First create a Timer:
[Nst1_scheduledtimerwithtimeinterval: 1
Target: Self
Selector: @ selector (
Mymethod)
Userinfo:
Myobject
Repeats: Yes];
2. then pass the nstimer object to the handler:
-(Void)
Mymethod:
(Nstmer *) Timer{
// Now I can access all the properties and methods
Myobject
[
[Timer userinfo]Myobjectmethod];
}
Use "invalidate" to stop the timer:
[Mytimer invalidate];
Mytimer = nil; // ensures we never invalidate an already invalid timer application analysis when the application is released, we may need to collect some data, such as how often the program is used. Most people use pinchmedia. They will provide the obj-C code that we can easily add to the program, and then we can view the statistics through their website. Timecalculate the passage of time by using
Cfabsolutetimegetcurrent ().
Cfabsolutetime mycurrenttime = cfabsolutetimegetcurrent ();
// The perform calculations here warning window displays a simple warning window with the OK button.
Uialertview * Alert = [[uialertview alloc] initwithtitle: Nil message: @ "an alert! "
Delegate: Self cancelbuttontitle: @ "OK" otherbuttontitles: Nil];
[Alert show];
[Alert release]; a specific plist file of the plist file can be saved to the resources folder of the app bundle. When the application runs, it checks whether there is a plist file in the user's documents folder. If not, it will be copied from the app bundle directory.
// Look in statements for an existing plist File
Nsarray * paths = nssearchpathfordirectoriesindomains (
Nsdocumentdirectory, nsuserdomainmask, yes );
Nsstring * documentsdirectory = [paths objectatindex: 0];
Myplistpath = [documentsdirectory stringbyappendingpathcomponent:
[Nsstring stringwithformat: @ "% @. plist", plistname];
[Myplistpath retain];
// If it's not there, copy it from the bundle
Nsfilemanager * filemanger = [nsfilemanager defaultmanager];
If (! [Filemanger fileexistsatpath: myplistpath]) {
Nsstring * pathtosettingsinbundle = [nsbundle mainbundle]
Pathforresource: plistname oftype: @ "plist"];
}
Now we can read the plist file from the Documents folder.
Nsarray * paths = nssearchpathfordirectoriesindomains (
Nsdocumentdirectory, nsuserdomainmask, yes );
Nsstring * documentsdirectorypath = [paths objectatindex: 0];
Nsstring * Path = [documentsdirectorypath
Stringbyappendingpathcomponent: @ "MyApp. plist"];
Nsmutabledictionary * plist = [nsdictionary dictionarywithcontentsoffile: path];
Now read and set key/Values
Mykey = (INT) [[plist valueforkey: @ "mykey"] intvalue];
Mykey2 = (bool) [[plist valueforkey: @ "mykey2"] boolvalue];
[Plist setvalue: mykey forkey: @ "mykey"];
[Plist writetofile: path atomically: Yes];
To facilitate the end-user to press the info button, we can increase the area that can be touched on the info button.
Cgrect newinfobuttonrect = cgrectmake (infobutton. Frame. Origin. x-25,
Infobutton. Frame. Origin. y-25, infobutton. Frame. Size. Width + 50,
Infobutton. Frame. Size. height + 50 );
[Infobutton setframe: newinfobuttonrect]; find subviews (detecting subviews). We can find an existing view through a loop. When we use the tag attribute of view, we can easily implement detect subviews.
For (uiimageview * animage in [self. View subviews]) {
If (animage. Tag = 1 ){
// Do something
}
} Manual documentation
- Official Apple how-to's
- Learn objective-C