iOS開發(fā)常用代碼_第1頁
iOS開發(fā)常用代碼_第2頁
iOS開發(fā)常用代碼_第3頁
iOS開發(fā)常用代碼_第4頁
iOS開發(fā)常用代碼_第5頁
免費預(yù)覽已結(jié)束,剩余23頁可下載查看

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quá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:%,astring);astringrelease;

2、3、在以上方法中,提升速度:initWithString 方法NSString*astring=NSStringallocinitWithString:ThisisaString!;NSLog(astring:%,astring);astringrelease;4、用標準 c 創(chuàng)建字符串:initWithCString 方法char*Cstring=ThisisaString!;NSString*astring=NSStringallocinitWithCString:Cstring;NSLog(astring:%,astring);astringrelease;5、創(chuàng)建格式化字符串:占位符(

3、由一個加一個字符組成)inti=1;intj=2;NSString*astring=NSStringallocinitWithString:NSStringNSLog(astring:%,astring);astringrelease;6、創(chuàng)建臨時字符串NSString*astring;astring=NSStringstringWithCString:Thisisatemporarystring;NSLog(astring:%,astring);/*從文件讀取字符串:initWithContentsOfFile 方法*/NSString*path=astring.text;NSString*

4、astring=NSStringallocinitWithContentsOfFile:path;NSLog(astring:%,astring);astringrelease;/*寫字符串到文件:writeToFile 方法*/NSString*astring=NSStringallocinitWithString:ThisisaString!;NSLog(astring:%,astring);NSString*path=astring.text;astringwriteToFile:pathatomically:YES;用 C 比較:strcmp 函數(shù)charstring1=string!

5、;charstring2=string!;if(strcmp(string1,string2)=0)NSLog(1);isEqualToString 方法NSString*astring01=ThisisaString!;NSString*astring02=ThisisaString!;BOOLresult=astring01isEqualToString:astring02;NSLog(result:%d,result);compare 方法(comparer 返回的三種值)NSString*astring01=ThisisaString!;NSString*astring02=Thisi

6、saString!;BOOLresult=astring01compare:astring02=NSOrderedSame;NSLog(result:%d,result);NSOrderedSame 判斷兩者內(nèi)容是否相同NSString*astring01=ThisisaString!;NSString*astring02=thisisaString!;/*比較兩個字符串*/BOOLresult=astring01compare:astring02=NSOrderedAscending;NSLog(result:%d,result);/NSOrderedAscending 判斷兩對象值的大小(

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

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

9、astring02options:NSCaseInsensitiveSearch|NSNumericSearch=NSOrderedSame;NSLog(result:%d,result);/NSCaseInsensitiveSearch:不區(qū)分大小寫比較 NSLiteralSearch:進行完全比較,區(qū)分大小寫 NSNumericSearch:比較字符串的字符個數(shù),而不是字符值。/*改變字符串的大小寫*/NSString*string1=AString;NSString*string2=String;NSLog(string1:%,string1uppercaseString);/大寫NSL

10、og(string2:%,string2lowercaseString);/小寫NSLog(string2:%,string2capitalizedString);/首字母大小/*在審中搜索子用*/NSString*string1=Thisisastring;NSString*string2=string;NSRangerange=stringlrangeOfString:string2;intlocation=range.location;intleight=range.length;NSString*astring=NSStringallocinitWithString:NSStrings

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

12、tring*string1=Thisisastring;NSString*string2=string1substringFromIndex:3;NSLog(string2:%,string2);-substringWithRange:/按照所給出的位置,長度,任意地從字符串中截取子用NSString*string1=Thisisastring;NSString*string2=string1substringW 計 hRange:NSMakeRange(0,4);NSLog(string2:%,string2);constchar*fieldValue=valuecStringUsingEn

13、coding:NSUTF8StringEncoding;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=

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

15、e;/獲取所有的時區(qū)名字NSArray*array=NSTimeZoneknownTimeZoneNames;/NSLog(array:%,array);/for 循環(huán)/for(inti=0;iarraycount;i+)/NSTimeZone*timeZone=NSTimeZonetimeZoneWithName:arrayobjectAtIndex:i;/formattersetTimeZone:timeZone;/NSString*locationTime=formatterstringFromDate:nowDate;/NSLog(”時區(qū)名字:時區(qū)當(dāng)前時間:,arrayobjectAt

16、Index:i,locationTime);/NSLog(timezonenameis:%”,arrayobjectAtIndex:i);/快速枚舉法for(NSString*timeZoneNameinarray)formattersetTimeZone:NSTimeZonetimeZoneWithName:timeZoneName;NSLog(%,%”,timeZoneName,formatterstringFromDate:nowDate);formatterrelease;nowDaterelease;NSCalendar 用法:-(NSString*)getWeek:(NSDate*

17、)dNSCalendar*calendar=NSCalendarallocinitW 讓 hCalendarIdentifier:NSGregorianCalendar;unsignedunits=NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit;NSDateComponents*components=calendarcomponents:unitsfromDate:d;calendarrelease;switch(componentsweekday)case 2:returnMonda

18、y;break;case 3:returnTuesday;break;case 4:returnWednesday;break;case 5:returnThursday;break;case 6:returnFriday;break;case 7:returnSaturday;break;case1:returnSunday;break;default:returnNoWeek;break;/用 components,我們可以讀取其他更多的數(shù)據(jù)4.用 Get 方式讀取網(wǎng)絡(luò)數(shù)據(jù):將網(wǎng)絡(luò)數(shù)讀取為字符串- (NSString*)getDataByURL:(NSString*)urlreturnNS

19、StringallocinitWithData:NSDatadataWithContentsOfURL:NSURLURLWithString:urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncodingencoding:NSUTF8StringEncoding;/讀取網(wǎng)絡(luò)圖片- (UIImage*)getImageByURL:(NSString*)urlreturnUllmageallocinitWithData:NSDatadataWithContentsOfURL:NSURLURLWithString:urlstring

20、ByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding;多線程NSThreaddetachNewThreadSelector:selector(scheduleTask)toTarget:selfwithObject:nil;- (void)scheduleTask/createapoolNSAutoreleasePool*pool=NSAutoreleasePoolallocinit;/releasethepool;poolrelease;/如果有參數(shù),則這么使用:NSThreaddetachNewThreadSelector:sel

21、ector(scheduleTask:)toTarget:selfwithObject:NSDatedate;- (void)scheduleTask:(NSDate*)mdate/createapoolNSAutoreleasePool*pool=NSAutoreleasePoolallocinit;/releasethepool;poolrelease;/注意 selector 里有冒號。/在線程里運行主線程里的方法selfperformSelectorOnMainThread:selector(moveToMain)withObject:nilwaitUntilDone:FALSE;6.

22、定時器 NSTimer 用法:代碼/一個可以自動關(guān)閉的 Alert 窗口UlAlertView*alert=UlAlertViewallocinitWithTitle:nilmessage:一個可以自動關(guān)閉的 Alert 窗口delegate:nilcancelButtonTitle:nil/NSLocalizedString(OK,OK)/取消任何按鈕otherButtonTitles:nil;/alertsetBounds:CGRectMake(alert.bounds.origin.x,alert.bounds.origin.y,alert.bounds.size.width,alert

23、.bounds.size.height+30.0);alertshow;UIActivityIndicatorView*indicator=UIActivityIndicatorViewallocinitWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge;/Adjusttheindicatorsoitisupafewpixelsfromthebottomofthealertindicator.center=CGPointMake(alert.bounds.size.width/2,alert.bounds.size

24、.height-40.0);indicatorstartAnimating;alertinsertSubview:indicatoratIndex:0;indicatorrelease;NSTimerscheduledTimerWithTimeInterval:3.0ftarget:selfselector:selector(dismissAlert:)userInfo:NSDictionarydictionaryWithObjectsAndKeys:alert,alert,testing,key,nil/如果不用傳遞參數(shù),那么可以將此項設(shè)置為 nil.repeats:NO;NSLog(rel

25、easealert);alertrelease;-(void)dismissAlert:(NSTimer*)timerNSLog(releasetimer);NSLog(timeruserInfoobjectForKey:key);UIAlertView*alert=timeruserInfoobjectForKey:alert;alertdismissW 讓 hClickedButtonIndex:0animated:YES;定時器停止使用:timerinvalidate;timer=nil;7.用戶缺省值 NSUserDefaults 讀?。?得到用戶缺省值NSUserDefaults*d

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

27、Log(LanguageCodeis%,currentLocaleobjectForKey:NSLocaleLanguageCode);NSLog(CountryCodeis%,currentLocaleobjectForKey:NSLocaleCountryCode8 .View 之間切換的動態(tài)效果設(shè)置:SettingsController*settings=SettingsControllerallocinitWithNibName:SettingsViewbundle:nil;settings.modalTransitionStyle=UIModalTransitionStyleFlip

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

29、id)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView11.鍵盤處理系列/settheUIKeyboardtoswitchtoadifferenttextfieldwhenyoupressreturn/switchtextFieldtothenameofyourtextfieldtextFieldbecomeFirstResponder;srandom(time(NULL);/隨機數(shù)種子idd=random();/隨機數(shù)4 .iPhone 的系統(tǒng)目錄:得至 UDocument 目錄:NSArray*paths=NSSear

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

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

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

33、ithButtonIndex:(NSInteger)buttonIndexNSLog(cancelactionSheet);/當(dāng)用戶按下 cancel 按鈕if(buttonindex=actionSheetcancelButtonIndex)exit(0);)/當(dāng)用戶按下 destructive 按鈕/if(buttonindex=actionSheetdestructiveButtonindex)/DoSomethinghere./)-(void)alertView:(UIAlertView*)alertViewwillDismissWithButtonindex:(NSinteger)b

34、uttonindexNSLog(cancelalertView);if(buttonindex=alertViewcancelButtonindex)exit(0);)10 .給 Window 設(shè)置全局的背景圖片:window.backgroundColor=UiColorcolorWithPatternimage:UiimageimageNamed:coolblack.png;11 .UlTextField 文本框顯示及對鍵盤的控制:代碼#pragmamark-#pragmamarkUlTextFieldDelegate/控制鍵盤跳轉(zhuǎn)-(BOOL)textFieldShouldReturn:

35、(UITextField*)textFieldif(textField=_txtAccount)if(_txtAccount.textlength=0)returnNO;_txtPasswordbecomeFirstResponder;elseif(textField=_txtPassword)_txtPasswordresignFirstResponder;returnYES;/輸入框背景更換-(BOOL)textFieldShouldBeginEditing:(UITextField*)textFieldtextFieldsetBackground:UIImageimageNamed:ct

36、ext_field_02.png;returnYES;-(void)textFieldDidEndEditing:(UITextField*)textFieldtextFieldsetBackground:UIImageimageNamed:ctext_field_01.png;12.UITextField 文本框前面空白寬度設(shè)置以及后面組合按鈕設(shè)置:代碼/給文本輸入框后面加入空白_txtAccount.rightView=_btnDropDown;_txtAccount.rightViewMode=UITextFieldViewModeAlways;/給文本輸入框前面加入空白CGRectfr

37、ame=_txtAccountframe;frame.size.width=5;UIView*leftview=UIViewallocinitWithFrame:frame;_txtAccount.leftViewMode=UITextFieldViewModeAlways;txtAccount.leftView=leftview;13 .UlScrollView 設(shè)置滑動不超出本身范圍:fcScrollViewsetBounces:NO;14 .在 drawRect 里畫文字:UIFont*f=UlFontsystemFontOfSize:20;UlColordarkGrayColorset

38、;NSString*text=hinKiloNet;textdrawAtPoint:CGPointMake(center.x,center.y)withFont:f;15. NSArray 查找是否存在對象時用 indexOfObject,如果不存在則返回為NSNotFound.16. NString 與 NSArray 之間相互轉(zhuǎn)換:array=stringcomponentsSeparatedByString:,;string=arrayvalueForKey:descriptioncomponentsJoinedByString:,;17.TabController 隨意切換 tabba

39、r:self.tabBarControllersetSelectedIndex:tabIndex;或者 self.tabBarController.selectedIndex=tabIndex;或者實現(xiàn)下面的 delegate 來撲捉 tabbar 的事件:代碼-(BOOL)tabBarController:(UITabBarController*)tabBarControllershouldSelectViewController:(UIViewController*)viewControllerif(viewController.tabBarItem.titleisEqualToStrin

40、g:NSLocalizedString(Logout,nil)selfshowLogout;returnNO;returnYES;18.自定義 View 之間切換動畫:代碼-(void)pushController:(UIViewController*)controllerwithTransition:(UIViewAnimationTransition)transitionUlViewbeginAnimations:nilcontext:NULL;selfpushViewController:controlleranimated:NO;UIViewsetAnimationDuration:.5;UIViewsetAnimationBeginsFromCurrentState:YES;UIViewsetAnimationTransition:transitionforView:self.viewcache:YES;UIViewcommitAnimations;CATransition*transition=CATransitionanimation;transition.duration=kAnimationDuration;transition.timingFu

溫馨提示

  • 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)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論