iOS開發(fā)常用代碼_第1頁
iOS開發(fā)常用代碼_第2頁
iOS開發(fā)常用代碼_第3頁
iOS開發(fā)常用代碼_第4頁
iOS開發(fā)常用代碼_第5頁
已閱讀5頁,還剩28頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

1、iOS開發(fā)常用的代碼%c一個單一的字符%d一個十進制整數(shù)%i一個整數(shù)%e,%f,%g一個浮點數(shù)%o一個八進制數(shù)%s一個字符串%x一個十六進制數(shù)%p一個指針%n一個等于讀取字符數(shù)量的整數(shù)%u一個無符號整數(shù)%一個字符集%一個精度符號/一、NSString/*創(chuàng)建字符串的方法*/1、創(chuàng)建常量字符串。NSString*astring="ThisisaString!"2、創(chuàng)建空字符串,給予賦值。NSString*astring=NSStringallocinit;astring="ThisisaString!"NSLog("astring:%"

2、,astring);astringrelease;3、在以上方法中,提升速度:initWithString方法NSString*astring=NSStringallocinitWithString:"ThisisaString!"NSLog("astring:%",astring);astringrelease;4、用標(biāo)準(zhǔn)c創(chuàng)建字符串:initWithCString方法char*Cstring="ThisisaString!"NSString*astring=NSStringallocinitWithCString:Cstring;

3、NSLog("astring:%",astring);astringrelease;5、創(chuàng)建格式化字符串:占位符(由一個%加一個字符組成)inti=1;intj=2;NSString*astring=NSStringallocinitWithString:NSStringstringWithFormat:"%d.Thisis%istring!",i,j;NSLog("astring:%",astring);astringrelease;6、創(chuàng)建臨時字符串NSString*astring;astring=NSStringstringWi

4、thCString:"Thisisatemporarystring"NSLog("astring:%",astring);/*從文件讀取字符串:initWithContentsOfFile方法*/NSString*path="astring.text"NSString*astring=NSStringallocinitWithContentsOfFile:path;NSLog("astring:%",astring);astringrelease;/*寫字符串到文件:writeToFile方法*/NSString*

5、astring=NSStringallocinitWithString:"ThisisaString!"NSLog("astring:%",astring);NSString*path="astring.text"astringwriteToFile:pathatomically:YES;astringrelease;/*比較兩個字符串*/用C比較:strcmp函數(shù)charstring1="string!"charstring2="string!"if(strcmp(string1,string

6、2)=0)NSLog("1");isEqualToString方法NSString*astring01="ThisisaString!"NSString*astring02="ThisisaString!"BOOLresult=astring01isEqualToString:astring02;NSLog("result:%d",result);compare方法(comparer返回的三種值)NSString*astring01="ThisisaString!"NSString*astrin

7、g02="ThisisaString!"BOOLresult=astring01compare:astring02=NSOrderedSame;NSLog("result:%d",result);NSOrderedSame判斷兩者內(nèi)容是否相同NSString*astring01="ThisisaString!"NSString*astring02="thisisaString!"BOOLresult=astring01compare:astring02=NSOrderedAscending;NSLog("

8、result:%d",result);/NSOrderedAscending判斷兩對象值的大小(按字母順序進行比較,astring02大于astring01為真)NSString*astring01="thisisaString!"NSString*astring02="ThisisaString!"BOOLresult=astring01compare:astring02=NSOrderedDescending;NSLog("result:%d",result);/NSOrderedDescending判斷兩對象值的大小(

9、按字母順序進行比較,astring02小于astring01為真)不考慮大小寫比較字符串1NSString*astring01="thisisaString!"NSString*astring02="ThisisaString!"BOOLresult=astring01caseInsensitiveCompare:astring02=NSOrderedSame;NSLog("result:%d",result);/NSOrderedDescending判斷兩對象值的大小(按字母順序進行比較,astring02小于astring01為真

10、)不考慮大小寫比較字符串2NSString*astring01="thisisaString!"NSString*astring02="ThisisaString!"BOOLresult=astring01compare:astring02options:NSCaseInsensitiveSearch|NSNumericSearch=NSOrderedSame;NSLog("result:%d",result);/NSCaseInsensitiveSearch:不區(qū)分大小寫比較NSLiteralSearch:進行完全比較,區(qū)分大小寫N

11、SNumericSearch:比較字符串的字符個數(shù),而不是字符值。/*改變字符串的大小寫*/NSString*string1="AString"NSString*string2="String"NSLog("string1:%",string1uppercaseString);/大寫NSLog("string2:%",string2lowercaseString);/小寫NSLog("string2:%",string2capitalizedString);/首字母大小/*在串中搜索子串*/NS

12、String*string2="string"NSString*string1="Thisisastring"NSRangerange=string1rangeOfString:string2;intlocation=range.location;intleight=range.length;NSString*astring=NSStringallocinitWithString:NSStringstringWithFormat:"Location:%i,Leight:%i",location,leight;NSLog("a

13、string:%",astring);astringrelease;/*抽取子串*/但不包括該位,并包括之-substringToIndex:從字符串的開頭一直截取到指定的位置,置的字符NSString*string1="Thisisastring"NSString*string2=string1substringToIndex:3;NSLog("string2:%",string2);-substringFromIndex:以指定位置開始(包括指定位置的字符)后的全部字符NSString*string1="Thisisastring

14、"NSString*string2=string1substringFromIndex:3;-substringWithRange:/按照所給出的位置,長度,任意地從字符串中截取子串NSString*string1="Thisisastring"NSString*string2=string1substringWithRange:NSMakeRange(0,4);NSLog("string2:%",string2);constchar*fieldValue=valuecStringUsingEncoding:NSUTF8StringEncodi

15、ng;constchar*fieldValue=valueUTF8String;NSString轉(zhuǎn)NSDataNSString*str="kilonet"NSData*data=strdataUsingEncoding:NSUTF8StringEncoding;Dateformat用法:-(NSString*)getDay:(NSDate*)dNSString*s;NSDateFormatter*format=NSDateFormatterallocinit;formatsetDateFormat:"YYYY/MM/ddhh:mm:ss"s=format

16、stringFromDate:d;formatrelease;returns;各地時區(qū)獲取:NSDate*nowDate=NSDatenew;NSDateFormatter*formatter=NSDateFormatterallocinit;formattersetDateFormat:"yyyy/MM/ddHH:mm:ss"/根據(jù)時區(qū)名字獲取當(dāng)前時間,如果該時區(qū)不存在,默認(rèn)獲取系統(tǒng)當(dāng)前時區(qū)的時間/NSTimeZone*timeZone=NSTimeZonetimeZoneWithName:"Europe/Andorra"/formattersetTi

17、meZone:timeZone;/獲取所有的時區(qū)名字NSArray*array=NSTimeZoneknownTimeZoneNames;/NSLog("array:%",array);/for循環(huán)/for(inti=0;i<arraycount;i+)/NSTimeZone*timeZone=NSTimeZonetimeZoneWithName:arrayobjectAtIndex:i;/formattersetTimeZone:timeZone;/NSString*locationTime=formatterstringFromDate:nowDate;/NSLo

18、g("時區(qū)名字:%:時區(qū)當(dāng)前時間:%",arrayobjectAtIndex:i,locationTime);/NSLog("timezonenameis:%",arrayobjectAtIndex:i);/快速枚舉法for(NSString*timeZoneNameinarray)formattersetTimeZone:NSTimeZonetimeZoneWithName:timeZoneName;NSLog("%,%",timeZoneName,formatterstringFromDate:nowDate);formatter

19、release;nowDaterelease;NSCalendar用法:-(NSString*)getWeek:(NSDate*)dNSCalendar*calendar=NSCalendarallocinitWithCalendarIdentifier:NSGregorianCalendar;unsignedunits=NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit;NSDateComponents*components=calendarcomponents:unitsfromDat

20、e:d;calendarrelease;switch(componentsweekday)case2:return"Monday"break;case3:return"Tuesday"break;case4:return"Wednesday"break;case5:return"Thursday"break;case6:return"Friday"break;case7:return"Saturday"break;case1:return"Sunday"b

21、reak;default:return"NoWeek"break;/用components,我們可以讀取其他更多的數(shù)據(jù)4.用Get方式讀取網(wǎng)絡(luò)數(shù)據(jù):將網(wǎng)絡(luò)數(shù)讀取為字符串-(NSString*)getDataByURL:(NSString*)urlreturnNSStringallocinitWithData:NSDatadataWithContentsOfURL:NSURLURLWithString:urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncodingencoding:NSUTF8StringEn

22、coding;/讀取網(wǎng)絡(luò)圖片-(UIImage*)getImageByURL:(NSString*)urlreturnUIImageallocinitWithData:NSDatadataWithContentsOfURL:NSURLURLWithString:urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding;多線程NSThreaddetachNewThreadSelector:selector(scheduleTask)toTarget:selfwithObject:nil;-(void)scheduleTas

23、k/createapoolNSAutoreleasePool*pool=NSAutoreleasePoolallocinit;/releasethepool;poolrelease;/如果有參數(shù),則這么使用:NSThreaddetachNewThreadSelector:selector(scheduleTask:)toTarget:selfwithObject:NSDatedate;-(void)scheduleTask:(NSDate*)mdate/createapoolNSAutoreleasePool*pool=NSAutoreleasePoolallocinit;/releaseth

24、epool;poolrelease;/注意selector里有冒號。/在線程里運行主線程里的方法selfperformSelectorOnMainThread:selector(moveToMain)withObject:nilwaitUntilDone:FALSE;6. 定時器NSTimer用法:代碼/一個可以自動關(guān)閉的Alert窗口UIAlertView*alert=UIAlertViewallocinitWithTitle:nilmessage:"一個可以自動關(guān)閉的Alert窗口"delegate:nilcancelButtonTitle:nil/NSLocalize

25、dString("OK","OK")/取消任何按鈕otherButtonTitles:nil;/alertsetBounds:CGRectMake(alert.bounds.origin.x,alert.bounds.origin.y,alert.bounds.size.width,alert.bounds.size.height+30.0);alertshow;UIActivityIndicatorView*indicator=UIActivityIndicatorViewallocinitWithActivityIndicatorStyle:UIAc

26、tivityIndicatorViewStyleWhiteLarge;/Adjusttheindicatorsoitisupafewpixelsfromthebottomofthealertindicator.center=CGPointMake(alert.bounds.size.width/2,alert.bounds.size.height-40.0);indicatorstartAnimating;alertinsertSubview:indicatoratIndex:0;indicatorrelease;NSTimerscheduledTimerWithTimeInterval:3.

27、0ftarget:selfselector:selector(dismissAlert:)userInfo:NSDictionarydictionaryWithObjectsAndKeys:alert,"alert","testing","key",nil/如果不用傳遞參數(shù),那么可以將此項設(shè)置為nil.repeats:NO;NSLog("releasealert");alertrelease;-(void)dismissAlert:(NSTimer*)timerNSLog("releasetimer&qu

28、ot;);NSLog(timeruserInfoobjectForKey:"key");UIAlertView*alert=timeruserInfoobjectForKey:"alert"alertdismissWithClickedButtonIndex:0animated:YES;定時器停止使用:timerinvalidate;timer=nil;7. 用戶缺省值NSUserDefaults讀?。?得到用戶缺省值NSUserDefaults*defs=NSUserDefaultsstandardUserDefaults;/在缺省值中找到AppleL

29、anguages,返回值是一個數(shù)組NSArray*languages=defsobjectForKey:"AppleLanguages"NSLog("alllanguage語言is%",languages);/在得到的數(shù)組中的第一個項就是用戶的首選語言了NSLog("首選語言is%",languagesobjectAtIndex:0);/getthelanguage&countrycodeNSLocale*currentLocale=NSLocalecurrentLocale;NSLog("LanguageCodei

30、s%",currentLocaleobjectForKey:NSLocaleLanguageCode);NSLog("CountryCodeis%",currentLocaleobjectForKey:NSLocaleCountryCode8. View之間切換的動態(tài)效果設(shè)置:SettingsController*settings=SettingsControllerallocinitWithNibName:"SettingsView"bundle:nil;settings.modalTransitionStyle=UIModalTransit

31、ionStyleFlipHorizontal;/水平翻轉(zhuǎn)selfpresentModalViewController:settingsanimated:YES;settingsrelease;9. NSScrollView滑動用法:-(void)scrollViewDidScroll:(UIScrollView*)scrollViewNSLog("正在滑動中.");/用戶直接滑動NSScrollView,可以看到滑動條-(void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView/通過其他控件觸發(fā)NSScrollV

32、iew滑動,看不到滑動條-(void)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView11.鍵盤處理系列/settheUIKeyboardtoswitchtoadifferenttextfieldwhenyoupressreturn/switchtextFieldtothenameofyourtextfieldtextFieldbecomeFirstResponder;srandom(time(NULL);/隨機數(shù)種子idd=random();/隨機數(shù)4. iPhone的系統(tǒng)目錄:/得到Document目錄:NSArray

33、*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);NSString*documentsDirectory=pathsobjectAtIndex:0;得到temp臨時目錄:NSString*tempPath=NSTemporaryDirectory();/得到目錄上的文件地址:文件NSString*文件地址=目錄地址stringByAppendingPathComponent:"名.擴展名"5. 狀態(tài)欄顯示Indicator:UIApplicationsha

34、redAworkActivityIndicatorVisible=YES;6. appIcon顯示數(shù)字:-(void)applicationDidEnterBackground:(UIApplication*)applicationUIApplicationsharedApplicationsetApplicationIconBadgeNumber:5;7. sqlite保存地址:代碼NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

35、NSString*thePath=pathsobjectAtIndex:0;NSString*filePath=thePathstringByAppendingPathComponent:"kilonet1.sqlite"NSString*dbPath=NSBundlemainBundleresourcePathstringByAppendingPathComponent:"kilonet2.sqlite"8. Application退出:exit(0);9. AlertView,ActionSheet的cancelButton點擊事件:代碼-(void

36、)actionSheet:(UIActionSheet*)actionSheetdidDismissWithButtonIndex:(NSInteger)buttonIndexNSLog("cancelactionSheet");/當(dāng)用戶按下cancel按鈕if(buttonIndex=actionSheetcancelButtonIndex)exit(0);/當(dāng)用戶按下destructive按鈕/if(buttonIndex=actionSheetdestructiveButtonIndex)/DoSomethinghere./-(void)alertView:(UIAl

37、ertView*)alertViewwillDismissWithButtonIndex:(NSInteger)buttonIndexNSLog("cancelalertView");if(buttonIndex=alertViewcancelButtonIndex)exit(0);10. 給Window設(shè)置全局的背景圖片:window.backgroundColor=UIColorcolorWithPatternImage:UIImageimageNamed:"coolblack.png"11. UITextField文本框顯示及對鍵盤的控制代碼#pr

38、agmamark-#pragmamarkUITextFieldDelegate/控制鍵盤跳轉(zhuǎn)-(BOOL)textFieldShouldReturn:(UITextField*)textFieldif(textField=_txtAccount)if(_txtAccount.textlength=0)returnNO;_txtPasswordbecomeFirstResponder;elseif(textField=_txtPassword)_txtPasswordresignFirstResponder;returnYES;/輸入框背景更換-(BOOL)textFieldShouldBegi

39、nEditing:(UITextField*)textFieldtextFieldsetBackground:UIImageimageNamed:"ctext_field_02.png"returnYES;-(void)textFieldDidEndEditing:(UITextField*)textFieldtextFieldsetBackground:UIImageimageNamed:"ctext_field_01.png"12. UITextField文本框前面空白寬度設(shè)置以及后面組合按鈕設(shè)置:代碼/給文本輸入框后面加入空白_txtAccount

40、.rightView=_btnDropDown;_txtAccount.rightViewMode=UITextFieldViewModeAlways;/給文本輸入框前面加入空白CGRectframe=_txtAccountframe;frame.size.width=5;UIView*leftview=UIViewallocinitWithFrame:frame;_txtAccount.leftViewMode=UITextFieldViewModeAlways;_txtAccount.leftView=leftview;13. UIScrollView設(shè)置滑動不超出本身范圍:fcScrol

41、lViewsetBounces:NO;14. 在drawRect里畫文字:UIFont*f=UIFontsystemFontOfSize:20;UIColordarkGrayColorset;NSString*text="hinKiloNet"textdrawAtPoint:CGPointMake(center.x,center.y)withFont:f;15. NSArray查找是否存在對象時用indexOfObject,如果不存在則返回為NSNotFound.NString與NSArray之間相互轉(zhuǎn)換:array=stringcomponentsSeparatedByS

42、tring:","string=arrayvalueForKey:"description"componentsJoinedByString:","16. TabController隨意切換tabbar:self.tabBarControllersetSelectedIndex:tabIndex;或者self.tabBarController.selectedIndex=tabIndex;或者實現(xiàn)下面的delegate來撲捉tabbar的事件:代碼-(BOOL)tabBarController:(UITabBarController*

43、)tabBarControllershouldSelectViewController:(UIViewController*)viewControllerif(viewController.tabBarItem.titleisEqualToString:NSLocalizedString("Logout",nil)selfshowLogout;returnNO;returnYES;17. 自定義View之間切換動畫:代碼-(void)pushController:(UIViewController*)controllerwithTransition:(UIViewAnima

44、tionTransition)transitionUIViewbeginAnimations:nilcontext:NULL;selfpushViewController:controlleranimated:NO;UIViewsetAnimationDuration:.5;UIViewsetAnimationBeginsFromCurrentState:YES;UIViewsetAnimationTransition:transitionforView:self.viewcache:YES;UIViewcommitAnimations;CATransition*transition=CATransitionanimatio

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論