Skills in iPhone Development

Source: Internet
Author: User

1. nscalendar usage

-(Nsstring *) getweek :( nsdate *) d {nscalendar * Calendar = [[nscalendar alloc] calendar: nsgregoriancalendar]; unsigned Units = calendar | nsdaycalendarunit | nsweekcalendarunit; nsdatecomponents * components = [calendar components: unitsfromdate: d]; [calendar release]; Switch ([components weekday]) {case1: Return @ "Monday"; break; case2: return @ "Tuesday"; break; Case3: Return @ "Wednesday"; break; case4: Return @ "Thursday"; break; case5: Return @ "Friday"; break; case6: Return @ "Saturday "; break; case7: Return @ "Sunday"; break; default: Return @ "No Week"; break;} nslog (@ "% @", components );} 2. Read network data as a string-(nsstring *) getdatabyurl :( nsstring *) URL {return [[nsstring alloc] initwithdata: [nsdata datawithcontentsofurl: [nsurl urlwithstring: [URL Scheme Ingencoding: Custom] encoding: nsutf8stringencoding];} 3. Read the topology graph transform-(uiimage *) getimagebyurl :( nsstring *) URL {return [uiimage alloc] initwithdata: [nsdata datawithcontentsofurl: [nsurl urlwithstring: [url encoding: nsutf8stringencoding];} 4. multithreading (in this way, only threads are created, regardless of the thread to be recycled) [nsthread detachnewthreadselector: @ selector (scheduletask) totarget: Self withobject: Nil];-(VO ID) scheduletask {nutoreleasepool * Pool = [[nutoreleasepool alloc] init]; [pool release];} If a parameter exists, then [nsthread detachnewthreadselector: @ selector (scheduletask :) totarget: self withobject: [nsdate date];-(void) scheduletask :( nsdate *) mdate {ngutoreleasepool * Pool = [[ngutoreleasepool alloc] init]; [pool release];} run the callback method of the primary thread during thread failover [self-defined mselecw.mainthread: @ selector (movetomain) withobject: Nil W Aituntildone: false]; 5. Reading nsuserults ults from the Default User: nsuserdefaults * df = [nsuserdefaults standarduserdefaults]; nsarray * ages = [DF objectforkey: @ "applelanguages"]; nslog (@ "all language is % @", ages); nslog (@ "index is % @", [ages objectatindex: 0]); nslocale * currentlocale = [nslocale currentlocale]; nslog (@ "language code is % @", [currentlocale objectforkey: nslocalelanguagecode]); nslog (@ "Country C Ode is % @ ", [currentlocale objectforkey: nslocalecountrycode]); 6. Set the dynamic effect of conversion between views to secondviewcontroller * secondviewcontroller = [[secondviewcontroller alloc] init]; secondviewcontroller. modaltransitionstyle = uimodaltransitionstylefliphorizontal; // rotate horizontally [self. navigationcontroller presentmodalviewcontroller: secondviewcontroller animated: Yes]; [secondviewcontroller release]; 7. uiscrollview sliding usage:-(void) SCR Ollviewdidscroll :( uiscrollview *) scrollview {nslog (@ ") is sliding .. ")} // The user directly slides the uiscrollview and you can see the slide-(void) scrollviewdidenddelerating :( uiscrollview *) scrollview {} // triggers the uiscrollview slide through other controls, you cannot see the slide bar-(void) scrollviewdidendscrollinganimation :( uiscrollview *) scrollview {} // The sliding setting of uiscrollview does not go beyond the current range [scrollview setbounces: No: // obtain the document: Directory nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes); nsstring * documentsdirect Ory = [paths objectatindex: 0]; // obtain the temp temporary directory nsstring * tempath = nstemporarydirectory (); // obtain the file address nsstring * address = [paths stringbyappendingpathcomponent: @ "1.rtf"]; 9. the status bar displays indicator [uiapplication sharedapplication]. networkactivityindicatorvisible = yes; 10. The app icon displays numbers:-(void) applicationdidenterbackground :( uiapplication *) Application {[uiapplication sharedapplication] setapplicationiconbadgenu Mber: 5];} 11. SQLite address: nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectorynsuserdomainmask, yes); nsstring * thepath = [paths objectatindex: 0]; nsstring * filepath = [thepath stringbyappendingpathcomponent: @ "kilometer. SQLite "]; nsstring * dbpath = [[[nsbundle mainbundle] resourcepathstringbyappendingpathcomponent: @" kilometer2.sqlite "] Ield alloc] initwithframe: cgrectmake (100,150,260, 30)]; _ tspasswordtf. backgroundcolor = [uicolor redcolor]; _ tspasswordtf. tag = 2;/* use this method to release shared resources, save user data, _ tspasswordtf. delegate = self; [self. window addsubview: _ tspasswordtf];-(void) textfielddidbeginediting :( uitextfield *) textfield {[self animatetextfield: textfield up: Yes];}-(bool) textfieldshouldreturn :( u Itextfield *) textfield {[self animatetextfield: textfield up: No]; [textfield resignfirstresponder]; return yes;}-(void) animatetextfield: (uitextfield *) textfield up: (bool) up {const int movementdistance = 80; // tweak as needed const float movementduration = 0.3f; // tweak as neededint Movement = (up? -Movementdistance: movementdistance); [uiview beginanimations: Nil context: Nil]; [uiview setanimationbeginsfromcurrentstate: Yes]; [uiview setanimationduration: movementduration. window. frame = cgrectoffset (self. window. frame, 0, movement); [uiview commitanimations];} 13. Obtain the image ruler cgimageref IMG = [imageview. image cgimage]; nslog (@ "% d", cgimagegetwidth (IMG); nslog (@ "% d", cgimagegetheight (IMG); 1 4. alertview:-(void) alertview (uialertview *) alertview willdismisswithbuttonindex: (nsinteger) buttonindex; // before animation and hiding view {nslog (@ "cancel alertview... buttonindex = % d ", buttonindex); // when the Guest user presses the cancel button if (buttonindex = [alertview cancelbuttonindex]) {exit (0) ;}- (void) actionsheet :( uiactionsheet *) actionsheet diddismisswithbuttonindex :( nsinteger) Bu Ttonindex {nslog (@ "% S % d button = % d cancel actionsheet ..... ",__ function __,__ line __, buttonindex); // when a registrant presses the cancel button if (buttonindex = [actionsheet cancelbuttonindex]) {exit (0 );}} 15. set global background image self for window. window. backgroundcolor = [uicolor colorwithpatternimage: [uiimage imagenamed: @ ""]; 16. Change tabbar-(void) tabbarcontroller (uitabbarcontroller *) tabbarcontroller didselectviewcontroller :( Uiviewcontroller *) viewcontroller or-(bool) tabbarcontroller :( uitabbarcontroller *) tabbarcontroller shouldselectviewcontroller :( uiviewcontroller *) viewcontroller or _ tabbarcontroller. selectedindex = tabindex; 17. Calculated string degree: cgfloat W = [Title sizewithfont: [uifont fontwithname: @ "Arial" Size: 18]. width; 18. Calculate the shortest distance from a point to a line segment. Use the cllocation function to calculate the actual distance based on the result coordinate. Doublex1, Y1, X2, Y2, X3, Y3; double PX = x2-x1; double py = Y2-Y1; double som = px * px + py * py; double u = (X3-X1) * px + (Y3-Y1) * Py)/SOM; If (u> 1) {u = 1 ;} if (U <0) {u = 0;} // The closest pointdouble x = X1 + u * PX; Double Y = Y1 + u * py; double dx = x-X3; double DY = Y-Y3; double Dist = SQRT (dx * dx + dy * Dy); 19. uisearchbar background transparency when uisearchbar is used, setting the background to clearcolor or translucent to Yes cannot make the background transparent. Fan's research found a super simple and practical method: [[searchbar. subviews objectatindex: 0] removefromsuperview]; the background is completely eliminated, leaving only the search box itself. 20. Image and cache: uiimageview * wallpaper = [[uiimageview alloc] initwithimage: [uiimage imagenamed: @ "icon.png"]; // cached image uiimageview * wallpaper = [[uiimageview alloc] initwithimage: [uiimage imagewithcontentsoffile: @ "icon.png"]; // do not cache the image parts 21. The iPhone looks at the layer. // set the border of textview to rounded corner _ textview. layer. cornerradius = 8; _ textview. layer. maskstobounds = yes; // Add a colored border _ textview to textview. layer. borderwidth = 5; _ textview. Layer. bordercolor = [[uicolor colorwithred: 0.52 Green: 0.09 Blue: 0.07 ALPHA: 1] cgcolor]; // textview adds a background image _ textview. layer. contents = (ID) [uiimage imagenamed: @ "31"]. cgimage; 22. Close the current application [[uiapplication sharedapplication] performselector: @ selector (terminatewithsuccess)]; then [nsthread sleepfortimeinterval: 10.0]; The welcome page disappears after 10 seconds. 24. nsstring nsdate conversion nsstring * mystring = @ "testing"; nsdata * Data = [mystring datausingencoding: [nsstring defaultcstringencodi ng]; nsstring * astr = [[nsstring alloc] initwithdata: aData encoding: nsasciistringencoding]; 25. In uiwebview, if you want to display the datadetectortypes on the page as a link, click the phone number to make a call, in this case, you need to use datadetectortypes. Nsurl * url = [nsurl urlwithstring: @ "http://2015.iteye.com"]; nsurlrequest * requestobj = [nsurlrequest requestwithurl: url]; webview. datadetectortypes = uidatadetectortypephonenumber; [webview loadrequest: requestobj]; 26. Open the MACOs browser code. If you want to integrate the one-click open browser function in Mac software, you can use the following code [[nsworkspace sharedworkspace] openurls: URLs withappbundleidentifier: @ "com. apple. safari "Options: nsworkspacelaunchdefault additionaleve Ntparamdescriptor: NULL launchidentifiers: NULL]; 27. Set the statusbar and navigationbar style [uiapplication sharedapplication]. statusbarstyle = uistatusbarstyleblackopaque; self. navigationcontroller. navigationbar. barstyle = uibarstyleblack; 28. Hide the status bar. You may know a simple method, that is, add the following code to viewdidload of the program: [uiapplication sharedapplication]. statusbarhidden = yes; this method can hide state bars, but the problem is that the space occupied by state bars still cannot be used by the program. The method described in this article is still simple, but it is more effective. Add a key value to plist in three simple steps. 1. Right-click info. plist2. of the program, right-click any location, and select the new key value added by add row3. name it uistatusbarhidden or status bar is initially hidden, and select this item. 29. The optimal solution for generating random numbers arc4random () returns an integer. Therefore, the random number between 1 and 100 can be written as follows: arc4random () % 100 + 1; 30. Convert string and Char to nsstring * cocoastring = [[nsstring alloc] initwithstring: @ "mystring"]; const char * mycstring = [cocoastring cstring]; const char * cstring = "hello"; nsstring * cocostring = [[nsstring alloc] initwithcstring: cstring]; 31. Use uiwebview to open a webpage in the current program. If the URL contains Chinese characters, the Chinese characters in the URL must be converted into URLs. Nsstring * query = [nsstring stringwithformat: @ "http://www.baidu.com? Q = Apple "]; nsstring * strurl = [query failed: nsutf8stringencoding]; nsurl * url = [nsurl urlwithstring: strurl]; nsurlrequest * requestobj = [nsurlrequest requestwithurl: url]; [webview loadrequest: requestobj]; 32. Block the iOS device from locking the screen [[[uiapplication sharedapplication] setidletimerdisabled: Yes]; or [uiapplication sharedapplication]. idletimerdisabled = yes; 33. Run one command to uninstall xcode and iPhone sdksudo. /Developer/library/uninstall-devtools -- mode = All 34. Obtain the button's title-(void) btnpressed :( ID) sender {nsstring * Title = [Sender titleforstate: uicontrolstatenormal]; nsstring * newtext = [[nsstring alloc] initwithformat: @ "% @", title]; label. TEXT = newtext; [newtext release];} 35. nsdate to nsstringnsstring * datestr = [[nsstring alloc] initwithformat: @ "% @", date]; or nsdateformatter * dateformatter = [[nsdateforma Tter alloc] init]; [dateformatter setdateformat: @ "yyyy-mm-dd hh: mm: SS"]; nsstring * strdate = [dateformatter stringfromdate: [nsdate date]; nslog (@ "% @", strdate); [dateformatter release]; 36. uiimageview * imageview = [[uiimageview alloc] initwithframe: cgrectmake (0, 0, 0, 0)]; [imageview setimage: [uiimage imagenamed: @ "4.jpg"]; self. animageview = imageview; [self. view addsubview: imageview]; [I Mageview release]; cgcontextref context = uigraphicsgetcurrentcontext (); [uiview beginanimations: Nil context: Context]; [uiview setanimationcurve: Custom]; [uiview setanimationduration: 2.5]; cgimageref IMG = [self. animageview. image cgimage]; [animageview setframe: cgrectmake (0, 0, cgimagegetwidth (IMG), cgimagegetheight (IMG)]; [uiview commitanimations]; nslog (@ "% lu ", cgimagegetwidth (IMG); nslog (@ "% lu", cgimagegetheight (IMG); 37. Convert the number to the string nsstring * newtext = [[nsstring alloc] initwithformat: @ "% d ", number]; numberlabel. TEXT = newtext; [newtext release]; 38. Use of the random function arc4random. in the iPhone, rand_max is 0x7fffffff (2147483647), while the maximum value returned by arc4random () is 0x100000000 (4294967296), thus providing better precision. You do not need to generate random seeds when using arc4random (), because it is automatically generated when you call it for the first time. For example, arc4random () is used to obtain floating point numbers between 0 and 100 # define arc4random_max 0x00000000double val = floround (double) arc4random ()/arc4random_max) * 1000000f); 1. self. view. backgroundcolor = [uicolor colorwithhue: arc4random () % 2 55/2552. 3. 4. saturation: arc4random () % 2 brightness: arc4random () % 2 alpha: 1.0]; 39. You can change the keyboard color of the iPhone and iPod Touch through the code to better match the interface style of the app, the following code is used to change the color of the iPhone keyboard. -(Void) textfielddidbeginediting :( uitextfield *) textfield {nsarray * Ws = [[uiapplication sharedapplication] windows]; for (uiview * w in WS) {nsarray * Vs = [W subviews]; for (uiview * V in)

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.