iOS开发常用代码_第1页
iOS开发常用代码_第2页
iOS开发常用代码_第3页
iOS开发常用代码_第4页
iOS开发常用代码_第5页
已阅读5页,还剩23页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、iOS 开发常用的代码%c 一个单一的字符%d 一个十进制整数%i 一个整数%e,%f,%g 一个浮点数%o 一个八进制数%s 一个字符串%x 一个十六进制数%p 一个指针%n 一个等于读取字符数量的整数%u 一个无符号整数%一个字符集%一个精度符号一、NSString/*创建字符串的方法*/1、创建常量字符串。NSString*astring=ThisisaString!;2、创建空字符串,给予赋值NSString*astring=NSStringallocinit;astring=ThisisaString!;NSLog(astring:%,astring);astringrelease;

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

3、由一个加一个字符组成)inti=1;intj=2;NSString*astring=NSStringallocinitWithString:NSStringNSLog(astring:%,astring);astringrelease;6、创建临时字符串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 函数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 判断两者内容是否相同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:不区分大小写比较 NSLiteralSearch:进行完全比较,区分大小写 NSNumericSearch:比较字符串的字符个数,而不是字符值。/*改变字符串的大小写*/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 转 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;)各地时区获取:NSDate*nowDate=NSDatenew;NSDateFormatter*formatter=NSDateFormatterallocinit;formattersetDateFormat:yyyy/MM/ddHH:mm:ss;/根据时区名字获取当前时间,如果该时区不存在,默认获取系统当前时区的时间/NSTimeZone*timeZone=NSTimeZonetimeZoneW 计 hName:Europe/Andorra;/formattersetTimeZone:timeZon

15、e;/获取所有的时区名字NSArray*array=NSTimeZoneknownTimeZoneNames;/NSLog(array:%,array);/for 循环/for(inti=0;iarraycount;i+)/NSTimeZone*timeZone=NSTimeZonetimeZoneWithName:arrayobjectAtIndex:i;/formattersetTimeZone:timeZone;/NSString*locationTime=formatterstringFromDate:nowDate;/NSLog(”时区名字:时区当前时间:,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,我们可以读取其他更多的数据4.用 Get 方式读取网络数据:将网络数读取为字符串- (NSString*)getDataByURL:(NSString*)urlreturnNS

19、StringallocinitWithData:NSDatadataWithContentsOfURL:NSURLURLWithString:urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncodingencoding:NSUTF8StringEncoding;/读取网络图片- (UIImage*)getImageByURL:(NSString*)urlreturnUllmageallocinitWithData:NSDatadataWithContentsOfURL:NSURLURLWithString:urlstring

20、ByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding;多线程NSThreaddetachNewThreadSelector:selector(scheduleTask)toTarget:selfwithObject:nil;- (void)scheduleTask/createapoolNSAutoreleasePool*pool=NSAutoreleasePoolallocinit;/releasethepool;poolrelease;/如果有参数,则这么使用: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 用法:代码/一个可以自动关闭的 Alert 窗口UlAlertView*alert=UlAlertViewallocinitWithTitle:nilmessage:一个可以自动关闭的 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/如果不用传递参数,那么可以将此项设置为 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,返回值是一个数组NSArray*languages=defsobjectForKey:AppleLanguages;NSLog(alllanguage 语言 is%,languages);/在得到的数组中的第一个项就是用户的首选语言了NSLog(”首选语言 is%,languagesobjectAtIndex:0);/getthelanguage&countrycodeNSLocale*currentLocale=NSLocalecurrentLocale;NS

27、Log(LanguageCodeis%,currentLocaleobjectForKey:NSLocaleLanguageCode);NSLog(CountryCodeis%,currentLocaleobjectForKey:NSLocaleCountryCode8 .View 之间切换的动态效果设置:SettingsController*settings=SettingsControllerallocinitWithNibName:SettingsViewbundle:nil;settings.modalTransitionStyle=UIModalTransitionStyleFlip

28、Horizontal;水平翻转selfpresentModalViewController:settingsanimated:YES;settingsrelease;9 .NSScrollView 滑动用法:- (void)scrollViewDidScroll:(UIScrollView*)scrollViewNSLog(正在滑动中.”);/用户直接滑动 NSScrollView,可以看到滑动条- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView/通过其他才$件触发 NSScrollView 滑动,看不到滑动条- (vo

29、id)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView11.键盘处理系列/settheUIKeyboardtoswitchtoadifferenttextfieldwhenyoupressreturn/switchtextFieldtothenameofyourtextfieldtextFieldbecomeFirstResponder;srandom(time(NULL);/随机数种子idd=random();/随机数4 .iPhone 的系统目录:得至 UDocument 目录:NSArray*paths=NSSear

30、chPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);NSString*documentsDirectory=pathsobjectAtIndex:0;得到 temp 临时目录:NSString*tempPath=NSTemporaryDirectory();/得到目录上的文件地址:NSString*文件地址=目录地址 stringByAppendingPathComponent:”文件名.扩展名;5 .状态栏显示 Indicator:UlApplicationsharedAworkActivityInd

31、icatorVisible=YES;6 .appIcon 显示数字:-(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);/当用户按下 cancel 按钮if(buttonindex=actionSheetcancelButtonIndex)exit(0);)/当用户按下 destructive 按钮/if(buttonindex=actionSheetdestructiveButtonindex)/DoSomethinghere./)-(void)alertView:(UIAlertView*)alertViewwillDismissWithButtonindex:(NSinteger)b

34、uttonindexNSLog(cancelalertView);if(buttonindex=alertViewcancelButtonindex)exit(0);)10 .给 Window 设置全局的背景图片:window.backgroundColor=UiColorcolorWithPatternimage:UiimageimageNamed:coolblack.png;11 .UlTextField 文本框显示及对键盘的控制:代码#pragmamark-#pragmamarkUlTextFieldDelegate/控制键盘跳转-(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 文本框前面空白宽度设置以及后面组合按钮设置:代码/给文本输入框后面加入空白_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 设置滑动不超出本身范围: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 之间相互转换:array=stringcomponentsSeparatedByString:,;string=arrayvalueForKey:descriptioncomponentsJoinedByString:,;17.TabController 随意切换 tabba

39、r:self.tabBarControllersetSelectedIndex:tabIndex;或者 self.tabBarController.selectedIndex=tabIndex;或者实现下面的 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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论