《2022年iOS开发常用代码 .pdf》由会员分享,可在线阅读,更多相关《2022年iOS开发常用代码 .pdf(29页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、iOS开发常用代码%c 一个单一的字符%d 一个十进制整数%i一个整数%e, %f, %g 一个浮点数%o 一个八进制数%s 一个字符串%x 一个十六进制数%p 一个指针%n 一个等于读取字符数量的整数%u 一个无符号整数% 一个字符集% 一个精度符号/一、NSString /*- 创建字符串的方法 -*/ 1、创建常量字符串。NSString *astring = This is a String!; 2、创建空字符串,给予赋值。名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 1
2、页,共 29 页 - - - - - - - - - NSString *astring = NSStringalloc init; astring = This is a String!; NSLog(astring:%,astring); astring release; 3、在以上方法中,提升速度:initWithString 方法NSString *astring = NSStringalloc initWithString:This is a String!; NSLog(astring:%,astring); astring release; 4、用标准 c创建字符串 :initW
3、ithCString 方法char *Cstring = This is a String!; NSString *astring = NSStringalloc initWithCString:Cstring; NSLog(astring:%,astring); astring release; 5、创建格式化字符串 :占位符(由一个 %加一个字符组成)inti = 1; int j = 2; NSString *astring = NSStringalloc initWithString:NSStringstringWithFormat:%d.This is %i string!,i,j;
4、 NSLog(astring:%,astring); 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 2 页,共 29 页 - - - - - - - - - astring release; 6、创建临时字符串NSString *astring; astring = NSStringstringWithCString:This is a temporary string; NSLog(astring:%,astring); /*- 从文件读取字符串 :initWithContent
5、sOfFile方法-*/ NSString *path = astring.text; NSString *astring = NSStringalloc initWithContentsOfFile:path; NSLog(astring:%,astring); astring release; /*- 写字符串到文件 :writeToFile 方法 -*/ NSString *astring = NSStringalloc initWithString:This is a String!; NSLog(astring:%,astring); NSString *path = astring
6、.text; astringwriteToFile: path atomically: YES; astring release; /*- 比较两个字符串 -*/ 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 3 页,共 29 页 - - - - - - - - - 用C比较:strcmp函数char string1 = string!; char string2 = string!; if(strcmp(string1, string2) = = 0) NSLog(1); isE
7、qualToString 方法NSString *astring01 = This is a String!; NSString *astring02 = This is a String!; BOOL result = astring01 isEqualToString:astring02; NSLog(result:%d,result); compare 方法(comparer 返回的三种值 ) NSString *astring01 = This is a String!; NSString *astring02 = This is a String!; BOOL result = as
8、tring01 compare:astring02 = = NSOrderedSame; NSLog(result:%d,result); NSOrderedSame 判断两者内容是否相同NSString *astring01 = This is a String!; 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 4 页,共 29 页 - - - - - - - - - NSString *astring02 = this is a String!; BOOL result = a
9、string01 compare:astring02 = = NSOrderedAscending; NSLog(result:%d,result); /NSOrderedAscending 判断两对象值的大小 (按字母顺序进行比较,astring02 大于astring01 为真) NSString *astring01 = this is a String!; NSString *astring02 = This is a String!; BOOL result = astring01 compare:astring02 = = NSOrderedDescending; NSLog(re
10、sult:%d,result); /NSOrderedDescending 判断两对象值的大小 (按字母顺序进行比较,astring02 小于astring01 为真) 不考虑大小写比较字符串1 NSString *astring01 = this is a String!; NSString *astring02 = This is a String!; BOOL result = astring01 caseInsensitiveCompare:astring02 = = NSOrderedSame; NSLog(result:%d,result); /NSOrderedDescendin
11、g 判断两对象值的大小 (按字母顺序进行比较,astring02 小于astring01 为真) 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 5 页,共 29 页 - - - - - - - - - 不考虑大小写比较字符串2 NSString *astring01 = this is a String!; NSString *astring02 = This is a String!; BOOL result = astring01 compare:astring02 optio
12、ns:NSCaseInsensitiveSearch | NSNumericSearch = = NSOrderedSame; NSLog(result:%d,result); /NSCaseInsensitiveSearch:不区分大小写比较 NSLiteralSearch: 进行完全比较,区分大小写 NSNumericSearch: 比较字符串的字符个数,而不是字符值。/*- 改变字符串的大小写 -*/ NSString *string1 = A String; NSString *string2 = String; NSLog(string1:%,string1 uppercaseStr
13、ing);/大写NSLog(string2:%,string2 lowercaseString);/小写NSLog(string2:%,string2 capitalizedString);/首字母大小/*- 在串中搜索子串-*/ NSString *string1 = This is a string; NSString *string2 = string; NSRange range = string1 rangeOfString:string2; int location = range.location; 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - -
14、 - - - - - - - - 名师精心整理 - - - - - - - 第 6 页,共 29 页 - - - - - - - - - intleight = range.length; NSString *astring = NSStringalloc initWithString:NSStringstringWithFormat:Location:%i,Leight:%i ,location,leight; NSLog(astring:%,astring); astring release; /*- 抽取子串-*/ -substringToIndex: 从字符串的开头一直截取到指定的位置
15、,但不包括该位置的字符NSString *string1 = This is a string; NSString *string2 = string1 substringToIndex:3; NSLog(string2:%,string2); -substringFromIndex: 以指定位置开始 (包括指定位置的字符) ,并包括之后的全部字符NSString *string1 = This is a string; NSString *string2 = string1 substringFromIndex:3; NSLog(string2:%,string2); -substringW
16、ithRange: / 按照所给出的位置,长度,任意地从字符串中截取子串名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 7 页,共 29 页 - - - - - - - - - NSString *string1 = This is a string; NSString *string2 = string1 substringWithRange:NSMakeRange(0, 4); NSLog(string2:%,string2); const char *fieldValue =
17、value cStringUsingEncoding:NSUTF8StringEncoding; const char *fieldValue = value UTF8String; NSString 转NSData NSString* str= kilonet; NSData* data=str dataUsingEncoding:NSUTF8StringEncoding; Date format 用法:-(NSString *) getDay:(NSDate *) d NSString *s ; NSDateFormatter *format = NSDateFormatteralloc
18、init; formatsetDateFormat:YYYY/MM/ddhh:mm:ss; s = format stringFromDate:d; format release; return s; 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 8 页,共 29 页 - - - - - - - - - 各地时区获取:NSDate *nowDate = NSDate new; NSDateFormatter *formatter = NSDateFormatteralloc ini
19、t; formattersetDateFormat:yyyy/MM/ddHH:mm:ss; / 根据时区名字获取当前时间,如果该时区不存在,默认获取系统当前时区的时间/ NSTimeZone* timeZone = NSTimeZonetimeZoneWithName:Europe/Andorra; / formattersetTimeZone:timeZone; /获取所有的时区名字NSArray *array = NSTimeZoneknownTimeZoneNames; / NSLog(array:%,array); /for循环/ for(inti=0;iarray count;i+)
20、 / / NSTimeZone* timeZone = NSTimeZonetimeZoneWithName:array objectAtIndex:i; / formattersetTimeZone:timeZone; / NSString *locationTime = formatter stringFromDate:nowDate; 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 9 页,共 29 页 - - - - - - - - - / NSLog( 时区名字 :% :
21、时区当前时间 : %,array objectAtIndex:i,locationTime); / /NSLog(timezone name is:%,array objectAtIndex:i); / /快速枚举法for(NSString *timeZoneName in array) formattersetTimeZone:NSTimeZonetimeZoneWithName:timeZoneName; NSLog(%,%,timeZoneName,formatter stringFromDate:nowDate); formatter release; nowDate release;
22、 NSCalendar 用法:-(NSString *) getWeek:(NSDate *) d NSCalendar *calendar = NSCalendaralloc initWithCalendarIdentifier:NSGregorianCalendar; unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit; NSDateComponents *components = calendar components:unitsfrom
23、Date:d; 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 10 页,共 29 页 - - - - - - - - - calendar release; switch (components weekday) case 2: return Monday; break; case 3: return Tuesday; break; case 4: return Wednesday; break; case 5: return Thursday; break; case 6: re
24、turn Friday; break; case 7: return Saturday; break; case 1: 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 11 页,共 29 页 - - - - - - - - - return Sunday; break; default: return No Week; break; / 用components ,我们可以读取其他更多的数据。 4. 用Get方式读取网络数据:将网络数读取为字符串- (NSString *) getDa
25、taByURL:(NSString *) url return NSStringalloc initWithData:NSDatadataWithContentsOfURL:NSURL URLWithString:url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding encoding:NSUTF8StringEncoding; /读取网络图片名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 12 页,共 2
26、9 页 - - - - - - - - - - (UIImage *) getImageByURL:(NSString *) url return UIImagealloc initWithData:NSDatadataWithContentsOfURL:NSURL URLWithString:url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding; 多线程NSThreaddetachNewThreadSelector:selector(scheduleTask) toTarget:selfwithObject:ni
27、l; -(void) scheduleTask /create a pool NSAutoreleasePool *pool = NSAutoreleasePoolalloc init; /release the pool; pool release; /如果有参数,则这么使用:NSThreaddetachNewThreadSelector:selector(scheduleTask:) toTarget:selfwithObject:NSDate date; 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - -
28、 - - - - - 第 13 页,共 29 页 - - - - - - - - - -(void) scheduleTask:(NSDate *) mdate /create a pool NSAutoreleasePool *pool = NSAutoreleasePoolalloc init; /release the pool; pool release; /注意selector 里有冒号。/在线程里运行主线程里的方法selfperformSelectorOnMainThread:selector(moveToMain) withObject:nilwaitUntilDone:FALS
29、E; 6. 定时器 NSTimer 用法: 代码/ 一个可以自动关闭的 Alert窗口UIAlertView *alert = UIAlertViewalloc initWithTitle:nil message: 一个可以自动关闭的 Alert窗口 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 14 页,共 29 页 - - - - - - - - - delegate:nil cancelButtonTitle:nil /NSLocalizedString(OK, OK) /取
30、消任何按钮otherButtonTitles:nil; /alertsetBounds:CGRectMake (alert.bounds.origin.x, alert.bounds.origin.y, alert.bounds.size.width, alert.bounds.size.height+30.0); alert show; UIActivityIndicatorView *indicator = UIActivityIndicatorViewalloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhit
31、eLarge; / Adjust the indicator so it is up a few pixels from the bottom of the alert indicator.center = CGPointMake(alert.bounds.size.width/2, alert.bounds.size.height-40.0); indicatorstartAnimating; alertinsertSubview:indicator atIndex:0; indicator release; NSTimer scheduledTimerWithTimeInterval:3.
32、0f target:self selector:selector(dismissAlert:) userInfo:NSDictionarydictionaryWithObjectsAndKeys:alert, 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 15 页,共 29 页 - - - - - - - - - alert, testing , key ,nil /如果不用传递参数,那么可以将此项设置为 nil. repeats:NO; NSLog(release alert);
33、 alert release; -(void) dismissAlert:(NSTimer *)timer NSLog(release timer); NSLog(timer userInfo objectForKey:key); UIAlertView *alert = timer userInfo objectForKey:alert; alert dismissWithClickedButtonIndex:0 animated:YES; 定时器停止使用:timer invalidate; timer = nil; 名师资料总结 - - -精品资料欢迎下载 - - - - - - - -
34、- - - - - - - - - - 名师精心整理 - - - - - - - 第 16 页,共 29 页 - - - - - - - - - 7. 用户缺省值 NSUserDefaults 读取:/得到用户缺省值NSUserDefaults *defs = NSUserDefaultsstandardUserDefaults; /在缺省值中找到 AppleLanguages, 返回值是一个数组NSArray* languages = defsobjectForKey:AppleLanguages; NSLog(all language 语言 is %, languages); /在得到的数
35、组中的第一个项就是用户的首选语言了NSLog( 首选语言is %,languages objectAtIndex:0); /get the language & country code NSLocale *currentLocale = NSLocalecurrentLocale; NSLog(Language Code is %, currentLocaleobjectForKey:NSLocaleLanguageCode); NSLog(Country Code is %, currentLocaleobjectForKey:NSLocaleCountryCode 8. View 之间切
36、换的动态效果设置:名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 17 页,共 29 页 - - - - - - - - - SettingsController *settings = SettingsControllerallocinitWithNibName:SettingsView bundle:nil; settings.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; /水平翻转selfpresent
37、ModalViewController:settingsanimated:YES; settings release; 9.NSScrollView 滑动用法:-(void) scrollViewDidScroll:(UIScrollView *)scrollView NSLog( 正在滑动中 .); /用户直接滑动 NSScrollView ,可以看到滑动条-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView / 通过其他控件触发 NSScrollView 滑动,看不到滑动条- (void) scrollViewDid
38、EndScrollingAnimation:(UIScrollView *)scrollView 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 18 页,共 29 页 - - - - - - - - - 11.键盘处理系列/set the UIKeyboard to switch to a different text field when you press return/switch textField to the name of your textfield textFie
39、ldbecomeFirstResponder; srandom(time(NULL); / 随机数种子id d = random(); / 随机数4. iPhone 的系统目录 : /得到Document 目录:NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = paths objectAtIndex:0; /得到temp临时目录:NSString *tempPath = NSTempora
40、ryDirectory(); 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 19 页,共 29 页 - - - - - - - - - /得到目录上的文件地址:NSString * 文件地址= 目录地址 stringByAppendingPathComponent:文件名 .扩展名 ; 5. 状态栏显示 Indicator :UIApplicationsharedAworkActivityIndicatorVisible = YES; 6.app Icon 显示数字:- (void
41、)applicationDidEnterBackground:(UIApplication *)application UIApplicationsharedApplication setApplicationIconBadgeNumber:5; 7.sqlite保存地址:代码NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *thePath = paths objectAtIndex:0; 名师资料总结 - - -精品资料欢迎下载
42、 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 20 页,共 29 页 - - - - - - - - - NSString *filePath = thePathstringByAppendingPathComponent:kilonet1.sqlite; NSString *dbPath = NSBundlemainBundle resourcePath stringByAppendingPathComponent:kilonet2.sqlite; 8.Application 退出: exit(0); 9. Alert
43、View ,ActionSheet 的cancelButton 点击事件:代码-(void) actionSheet :(UIActionSheet *) actionSheetdidDismissWithButtonIndex:(NSInteger) buttonIndex NSLog(cancel actionSheet.); /当用户按下 cancel 按钮if( buttonIndex = actionSheetcancelButtonIndex) exit(0); / /当用户按下 destructive 按钮/ if( buttonIndex = actionSheetdestru
44、ctiveButtonIndex) / / DoSomething here. / 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 21 页,共 29 页 - - - - - - - - - - (void)alertView:(UIAlertView *)alertViewwillDismissWithButtonIndex:(NSInteger)buttonIndex NSLog(cancel alertView.); if (buttonIndex = alertViewcan
45、celButtonIndex) exit(0); 10.给Window 设置全局的背景图片:window.backgroundColor = UIColorcolorWithPatternImage:UIImageimageNamed:coolblack.png; 11. UITextField 文本框显示及对键盘的控制: 代码#pragma mark - #pragma mark UITextFieldDelegate /控制键盘跳转- (BOOL)textFieldShouldReturn:(UITextField *)textField 名师资料总结 - - -精品资料欢迎下载 - -
46、- - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 22 页,共 29 页 - - - - - - - - - if (textField = _txtAccount) if (_txtAccount.text length=0) return NO; _txtPasswordbecomeFirstResponder; else if (textField = _txtPassword) _txtPasswordresignFirstResponder; return YES; /输入框背景更换-(BOOL) textFieldShou
47、ldBeginEditing:(UITextField *)textField textFieldsetBackground:UIImageimageNamed:ctext_field_02.png; return YES; -(void) textFieldDidEndEditing:(UITextField *)textField textFieldsetBackground:UIImageimageNamed:ctext_field_01.png; 名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - -
48、- - - - 第 23 页,共 29 页 - - - - - - - - - 12.UITextField 文本框前面空白宽度设置以及后面组合按钮设置:代码/给文本输入框后面加入空白_txtAccount.rightView = _btnDropDown; _txtAccount.rightViewMode = UITextFieldViewModeAlways; /给文本输入框前面加入空白CGRect frame = _txtAccount frame; frame.size.width = 5; UIView *leftview = UIViewalloc initWithFrame:f
49、rame; _txtAccount.leftViewMode = UITextFieldViewModeAlways; _txtAccount.leftView = leftview; 13. UIScrollView 设置滑动不超出本身范围:fcScrollViewsetBounces:NO; 14. 在drawRect 里画文字:名师资料总结 - - -精品资料欢迎下载 - - - - - - - - - - - - - - - - - - 名师精心整理 - - - - - - - 第 24 页,共 29 页 - - - - - - - - - UIFont * f = UIFont sy
50、stemFontOfSize:20; UIColordarkGrayColor set; NSString * text = hi nKiloNet; textdrawAtPoint:CGPointMake(center.x,center.y) withFont:f; 15. NSArray 查找是否存在对象时用 indexOfObject, 如果不存在则返回为NSNotFound. 16. NString 与NSArray 之间相互转换:array = string componentsSeparatedByString:,; string = array valueForKey:descr