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

下載本文檔

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

文檔簡(jiǎn)介

iOS開(kāi)發(fā)常用的代碼%c一個(gè)單一的字符%d一個(gè)十進(jìn)制整數(shù)%i一個(gè)整數(shù)%e,%f,%g一個(gè)浮點(diǎn)數(shù)%o一個(gè)八進(jìn)制數(shù)%s一個(gè)字符串%x一個(gè)十六進(jìn)制數(shù)%p一^指針%n一個(gè)等于讀取字符數(shù)量的整數(shù)%u一個(gè)無(wú)符號(hào)整數(shù)%[]一個(gè)字符集%%一個(gè)精度符號(hào)〃一、NSString/*創(chuàng)建字符串的方法*/1、創(chuàng)建常量字符串。NSString*astring=@"ThisisaString!";2、創(chuàng)建空字符串,給予賦值。NSString*astring=[[NSStringalloc]init];astring=@"ThisisaString!";NSLog(@"astring:%@",astring);[astringrelease];3、在以上方法中,提升速度:initWithString方法NSString*astring=[[NSStringalloc]initWithString:@"ThisisaString!"];NSLog(@"astring:%@”,astring);[astringrelease];4、用標(biāo)準(zhǔn)c創(chuàng)建字符串:initWithCString方法char*Cstring="ThisisaString!";NSString*astring=[[NSStringalloc]initWithCString:Cstring];NSLog(@"astring:%@",astring);[astringrelease];5、創(chuàng)建格式化字符串:占位符(由一個(gè)%加一個(gè)字符組成)inti=1;intj=2;NSString*astring=[[NSStringalloc]initWithString:[NSStringstringWithFormat:@"%d.Thisis%istring!",i,j]];NSLog(@"astring:%@",astring);[astringrelease];6、創(chuàng)建臨時(shí)字符串NSString*astring;astring=[NSStringstringWithCString:"Thisisatemporarystring"];NSLog(@"astring:%@",astring);/*從文件讀取字符串:initWithContentsOfFile方法*/NSString*path=@"astring.text";NSString*astring=[[NSStringalloc]initWithContentsOfFile:path];NSLog(@"astring:%@”,astring);[astringrelease];/*寫(xiě)字符串到文件:writeToFile方法*/NSString*astring=[[NSStringalloc]initWithString:@"ThisisaString!"];NSLog(@"astring:%@”,astring);NSString*path=@"astring.text";[astringwriteToFile:pathatomically:YES];/*比較兩個(gè)字符串*/用C比較:strcmp函數(shù)/*比較兩個(gè)字符串*/charstring1[]="string!";charstring2[]="string!";if(strcmp(string1,string2)==0)(NSLog(@"1");}isEqualToString方法NSString*astring01=@"ThisisaString!";NSString*astring02=@"ThisisaString!";BOOLresult=[astring01isEqualToString:astring02];NSLog(@"result:%d",result);compare方法(comparera回的三種值)NSString*astring01=@"ThisisaString!";NSString*astring02=@"ThisisaString!";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判斷兩對(duì)象值的大小(按字母順序進(jìn)行比較,astring02大于astring01為真)NSString*astring01=@"thisisaString!";NSString*astring02=@"ThisisaString!";BOOLresult=[astring01compare:astring02]==NSOrderedDescending;NSLog(@"result:%d",result);//NSOrderedDescending判斷兩對(duì)象值的大小(按字母順序進(jìn)行比較,astring02小于astring01為真)不考慮大小寫(xiě)比較字符串1NSString*astring01=@"thisisaString!";NSString*astring02=@"ThisisaString!";BOOLresult=[astring01caseInsensitiveCompare:astring02]==NSOrderedSame;NSLog(@"result:%d",result);//NSOrderedDescending判斷兩對(duì)象值的大小(按字母順序進(jìn)行比較,astring02小于astring01為真)不考慮大小寫(xiě)比較字符串2NSString*astring01=@"thisisaString!";NSString*astring02=@"ThisisaString!";BOOLresult=[astring01compare:astring02options:NSCaseInsensitiveSearch|NSNumericSearch]==NSOrderedSame;NSLog(@"result:%d”,result);//NSCaseInsensitiveSearch:不區(qū)分大小寫(xiě)比較NSLiteralSearch:進(jìn)行完全比較,區(qū)分大小寫(xiě)NSNumericSearch:比較字符串的字符個(gè)數(shù),而不是字符值。/*改變字符串的大小寫(xiě)*/NSString*string1=@"AString";NSString*string2=@"String";NSLog(@"string1:%@”,[string1uppercaseString]);//大寫(xiě)NSLog(@"string2:%@”,[string2lowercaseString]);//小寫(xiě)NSLog(@"string2:%@”,[string2capitalizedString]);//首字母大小/*在串中搜索子串*/NSString*string1=@"Thisisastring";NSString*string2=@"string";NSRangerange=[stringlrangeOfString:string2];intlocation=range.location;intleight=range.length;NSString*astring=[[NSStringalloc]initWithString:[NSStringstringWithFormat:@"Location:%i,Leight:%i",location,leight]];NSLog(@"astring:%@",astring);[astringrelease];/*抽取子串*/-substringToIndex:從字符串的開(kāi)頭一直截取到指定的位置,但不包括該位置的字符NSString*string1=@"Thisisastring";NSString*string2=[string1substringToIndex:3];NSLog(@"string2:%@”,string2);-substringFromIndex:以指定位置開(kāi)始(包括指定位置的字符),并包括之后的全部字符NSString*string1=@"Thisisastring";NSString*string2=[string1substringFromIndex:3];NSLog(@"string2:%@”,string2);-substringWithRange:〃按照所給出的位置,長(zhǎng)度,任意地從字符串中截取子串NSString*string1=@"Thisisastring";NSString*string2=[string1substringWithRange:NSMakeRange(0,4)];NSLog(@"string2:%@",string2);constchar*fieldValue=[valuecStringUsingEncoding:NSUTF8StringEncoding];constchar*fieldValue=[valueUTF8String];NSString轉(zhuǎn)NSDataNSString*str=@"kilonet";NSData*data=[strdataUsingEncoding:NSUTF8StringEncoding];Dateformat用法:-(NSString*)getDay:(NSDate*)d(NSString*s;NSDateFormatter*format=[[NSDateFormatteralloc]init];[formatsetDateFormat:@"YYYY/MM/ddhh:mm:ss"];s=[formatstringFromDate:d];[formatrelease];returns;}各地時(shí)區(qū)獲?。篘SDate*nowDate=[NSDatenew];NSDateFormatter*formatter=[[NSDateFormatteralloc]init];[formattersetDateFormat:@"yyyy/MM/ddHH:mm:ss"];//根據(jù)時(shí)區(qū)名字獲取當(dāng)前時(shí)間,如果該時(shí)區(qū)不存在,默認(rèn)獲取系統(tǒng)當(dāng)前時(shí)區(qū)的時(shí)間//NSTimeZone*timeZone=[NSTimeZonetimeZoneWithName:@"Europe/Andorra"];//[formattersetTimeZone:timeZone];〃獲取所有的時(shí)區(qū)名字NSArray*array=[NSTimeZoneknownTimeZoneNames];//NSLog(@"array:%@",array);//比「循環(huán)//for(inti=0;i<[arraycount];i++)//(//NSTimeZone*timeZone=[NSTimeZonetimeZoneWithName:[arrayobjectAtIndex:i]];//[formattersetTimeZone:timeZone];////NSString*locationTime=[formatterstringFromDate:nowDate];//NSLog(@"時(shí)區(qū)名字:%@:時(shí)區(qū)當(dāng)前時(shí)間:%@",[arrayobjectAtIndex:i],locationTime);////NSLog(@"timezonenameis:%@",[arrayobjectAtIndex:i]);//}〃快速枚舉法for(NSString*timeZoneNameinarray)([formattersetTimeZone:[NSTimeZonetimeZoneWithName:timeZoneName]];NSLog(@"%@,%@",timeZoneName,[formatterstringFromDate:nowDate]);}[formatterrelease];[nowDaterelease];NSCalendar用法:-(NSString*)getWeek:(NSDate*)d(NSCalendar*calendar=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];unsignedunits=NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit;NSDateComponents*components=[calendarcomponents:unitsfromDate: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";break;default:return@"NoWeek";break;}//用components,我們可以讀取其他更多的數(shù)據(jù)。}4.用Get方式讀取網(wǎng)絡(luò)數(shù)據(jù):將網(wǎng)絡(luò)數(shù)讀取為字符串-(NSString*)getDataByURL:(NSString*)url(return[[NSStringalloc]initWithData:[NSDatadataWithContentsOfURL:[NSURLURLWithString:[urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]encoding:NSUTF8StringEncoding];}〃讀取網(wǎng)絡(luò)圖片-(UIImage*)getImageByURL:(NSString*)url(return[[UIImagealloc]initWithData:[NSDatadataWithContentsOfURL:[NSURLURLWithString:[urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];}多線(xiàn)程[NSThreaddetachNewThreadSelector:@selector(scheduleTask)toTarget:selfwithObject:nil];-(void)scheduleTask(//createapoolNSAutoreleasePool*pool=[[NSAutoreleasePoolalloc]init];//releasethepool;[poolrelease];〃如果有參數(shù),則這么使用:[NSThreaddetachNewThreadSelector:@selector(scheduleTask:)toTarget:selfwithObject:[NSDatedate]];-(void)scheduleTask:(NSDate*)mdate(//createapoolNSAutoreleasePool*pool=[[NSAutoreleasePoolalloc]init];//releasethepool;[poolrelease];}〃注意selector里有冒號(hào)。〃在線(xiàn)程里運(yùn)行主線(xiàn)程里的方法[selfperformSelectorOnMainThread:@selector(moveToMain)withObject:nilwaitUntilDone:FALSE];定時(shí)器NSTimer用法:代碼//一個(gè)可以自動(dòng)關(guān)閉的Alert窗口UlAlertView*alert=[[UlAlertViewalloc]initWithTitle:nilmessage:[@"一^個(gè)可以自動(dòng)關(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.bounds.size.height+30.0)];[alertshow];UIActivityIndicatorView*indicator=[[UIActivityIndicatorViewalloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];//Adjusttheindicatorsoitisupafewpixelsfromthebottomofthealertindicator.center=CGPointMake(alert.bounds.size.width/2,alert.bounds.size.height-40.0);[indicatorstartAnimating];[alertinsertSubview:indicatoratIndex:0];[indicatorrelease];[NSTimerscheduledTimerWithTimeInterval:3.0ftarget:selfselector:@selector(dismissAlert:)userInfo:[NSDictionarydictionaryWithObjectsAndKeys:alert,@"alert",@"testing",@"key",nil]//如果不用傳遞參數(shù),那么可以將此項(xiàng)設(shè)置為nil.repeats:NO];NSLog(@"releasealert");[alertrelease];-(void)dismissAlert:(NSTimer*)timer(NSLog(@"releasetimer");NSLog([[timeruserInfo]objectForKey:@"key"]);UIAlertView*alert=[[timeruserInfo]objectForKey:@"alert"];[alertdismissWithClickedButtonIndex:0animated:YES];定時(shí)器停止使用:[timerinvalidate];timer=nil;用戶(hù)缺省值NSUserDefaults讀取:〃得到用戶(hù)缺省值NSUserDefaults*defs=[NSUserDefaultsstandardUserDefaults];〃在缺省值中找到AppleLanguages,返回值是一^數(shù)組NSArray*languages=[defsobjectForKey:@"AppleLanguages"];NSLog(@"alllanguage語(yǔ)言is%@",languages);〃在得到的數(shù)組中的第一個(gè)項(xiàng)就是用戶(hù)的首選語(yǔ)言了NSLog(@"首選語(yǔ)言is%@",[languagesobjectAtIndex:0]);//getthelanguage&countrycodeNSLocale*currentLocale=[NSLocalecurrentLocale];NSLog(@"LanguageCodeis%@",[currentLocaleobjectForKey:NSLocaleLanguageCode]);NSLog(@"CountryCodeis%@",[currentLocaleobjectForKey:NSLocaleCountryCodeView之間切換的動(dòng)態(tài)效果設(shè)置:SettingsController*settings=[[SettingsControlleralloc]initWithNibName:@"SettingsView"bundle:nil];settings.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;//水平翻轉(zhuǎn)[selfpresentModalViewController:settingsanimated:YES];[settingsrelease];NSScrollView滑動(dòng)用法:-(void)scrollViewDidScroll:(UIScrollView*)scrollView(NSLog(@"正在滑動(dòng)中...");}〃用戶(hù)直接滑動(dòng)NSScrollView,可以看到滑動(dòng)條-(void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView(//通過(guò)其他控件觸發(fā)NSScrollView滑動(dòng),看不到滑動(dòng)條-(void)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView(}11.鍵盤(pán)處理系列//settheUIKeyboardtoswitchtoadifferenttextfieldwhenyoupressreturn//switchtextFieldtothenameofyourtextfield[textFieldbecomeFirstResponder];srandom(time(NULL));//隨機(jī)數(shù)種子idd=random();//隨機(jī)數(shù)iPhone的系統(tǒng)目錄:〃得到Document目錄:NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);NSString*documentsDirectory=[pathsobjectAtIndex:0];〃得到temp臨時(shí)目錄:NSString*tempPath=NSTemporaryDirectory();〃得到目錄上的文件地址:NSString*文件地址=[目錄地址stringByAppendingPathComponent:@"文件名.擴(kuò)展名"];狀態(tài)欄顯示Indicator:[UIApplicationsharedApplication].networkActivityIndicatorVisible=YES;appIcon顯示數(shù)字:-(void)applicationDidEnterBackground:(UIApplication*)application([[UIApplicationsharedApplication]setApplicationIconBadgeNumber:5];sqlite保存地址:代碼NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);NSString*thePath=[pathsobjectAtIndex:0];NSString*filePath=[thePathstringByAppendingPathComponent:@"kilonet1.sqlite"];NSString*dbPath=[[[NSBundlemainBundle]resourcePath]stringByAppendingPathComponent:@"kilonet2.sqlite"];Application退出:exit(0);AlertView,ActionSheet的cancelButton點(diǎn)擊事件:代碼-(void)actionSheet:(UIActionSheet*)actionSheetdidDismissWithButtonIndex:(NSInteger)buttonIndex(NSLog(@"cancelactionSheet");〃當(dāng)用戶(hù)按下cancel按鈕if(buttonindex==[actionSheetcancelButtonIndex])(exit(0);}//〃當(dāng)用戶(hù)按下destructive按鈕//if(buttonindex==[actionSheetdestructiveButtonindex])(////DoSomethinghere.//}}-(void)alertView:(UIAlertView*)alertViewwillDismissWithButtonindex:(NSinteger)buttonindex(NSLog(@"cancelalertView");if(buttonindex==[alertViewcancelButtonindex])(exit(0);}}給Window設(shè)置全局的背景圖片:window.backgroundColor=[UiColorcolorWithPatternimage:[UiimageimageNamed:@"coolblack.png"]];UlTextField文本框顯示及對(duì)鍵盤(pán)的控制:代碼#pragmamark-#pragmamarkUITextFieldDelegate〃控制鍵盤(pán)跳轉(zhuǎn)-(BOOL)textFieldShouldReturn:(UITextField*)textField(if(textField==_txtAccount)(if([_txtAccount.textlength]==0)(returnNO;}[_txtPasswordbecomeFirstResponder];}elseif(textField==_txtPassword)([_txtPasswordresignFirstResponder];}returnYES;}〃輸入框背景更換-(BOOL)textFieldShouldBeginEditing:(UITextField*)textField([textFieldsetBackground:[UIImageimageNamed:@"ctext_field_02.png"]];returnYES;}-(void)textFieldDidEndEditing:(UITextField*)textField([textFieldsetBackground:[UIImageimageNamed:@"ctext_field_01.png"]];}UITextField文本框前面空白寬度設(shè)置以及后面組合按鈕設(shè)置:代碼〃給文本輸入框后面加入空白_txtAccount.rightView=_btnDropDown;_txtAccount.rightViewMode=UITextFieldViewModeAlways;〃給文本輸入框前面加入空白CGRectframe=[_txtAccountframe];frame.size.width=5;UIView*leftview=[[UIViewalloc]initWithFrame:frame];_txtAccount.leftViewMode=UITextFieldViewModeAlways;txtAccount.leftView=leftview;UlScrollView設(shè)置滑動(dòng)不超出本身范圍:[fcScrollViewsetBounces:NO];在drawRect里畫(huà)文字:UIFont*f=[UIFontsystemFontOfSize:20];[[UIColordarkGrayColor]set];NSString*text=@"hi\nKiloNet";[textdrawAtPoint:CGPointMake(center.x,center.y)withFont:f];NSArray查找是否存在對(duì)象時(shí)用indexOfObject,如果不存在則返回為NSNotFound.NString與NSArray之間相互轉(zhuǎn)換:array=[stringcomponentsSeparatedByString:@","];string=[[arrayvalueForKey:@"description"]componentsJoinedByString:@","];TabController隨意切換tabbar:[self.tabBarControllersetSelectedIndex:tabIndex];或者self.tabBarController.selectedIndex=tabIndex;或者實(shí)現(xiàn)下面的delegate來(lái)?yè)渥絫abbar的事件:代碼-(BOOL)tabBarController:(UITabBarController*)tabBarControllershouldSelectViewController:(UIViewController*)viewController(if([viewController.tabBarItem.titleisEqualToString:NSLocalizedString(@"Logout",nil)])([selfshowLogout];returnNO;}returnYES;}自定義View之間切換動(dòng)畫(huà):代碼-(void)pushController:(UIViewController*)controllerwithTransition:(UIViewAnimationTransition)transition[UlViewbeginAnimations:nilcontext:NULL];[selfpushViewController:controlleranimated:NO];[UIViewsetAnimationDuration:.5];[UIViewsetAnimationBeginsFromCurrentState:YES];[UIViewsetAnimationTransition:transitionforView:self.viewcache:YES];[UIViewcommitAnimations];}CATransition*transition=[CATransitionanimation];transition.duration=kAnimationDuratio

溫馨提示

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

最新文檔

評(píng)論

0/150

提交評(píng)論