iOS开发过程中的各种tips

前言

 iOS开发过程中,总有那么一些个小问题让人纠结,它们不会让程序崩溃,但是会让人崩溃。除此之外,还将分享一些细节现在我通过自己的总结以及从其他地方的引用,来总结一下一些常见小问题。 本篇长期更新,多积累,多奉献,同时感谢大家提出的宝贵更新意见!

 iOS高级开发实战讲解 

这是我在网上搜索到的iOS高级开发实战讲解,由于原文不是很方便浏览,所以我在这里整理一部分出来,方便查阅,同时谢谢大家。 这里我不是每一个都收录进来,这里只是放出一部分,有些用的太多,我就没整理了,大家如果想看可以去查看网上文章或者官网文档。 


1.返回输入键盘

- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
<span style="white-space:pre">	</span>[textField resignFirstResponder]; return YES; 
}

2.CGRect

CGRectFromString(<#NSString *string#>)//有字符串恢复出矩形 
CGRectInset(<#CGRect rect#>, <#CGFloat dx#>, <#CGFloat dy#>)//创建较小或者较大的矩形 
CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)//判断两巨星是否交叉,是否重叠 CGRectZero//高度和宽度为零的,位于(0,0)的矩形常量

3.隐藏状态栏

[UIApplication sharedApplication] setStatusBarHidden:<#(BOOL)#> withAnimation:<#(UIStatusBarAnimation)#>//隐藏状态栏 

4.自适应父视图的大小

self.view.autoresizesSubviews = YES; self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

5.UITableview的一些方法

这里我自己做了个测试,缩进级别设置为行号,row越大,缩进越多 
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
<span style="white-space:pre">	</span> NSInteger row = indexPath.row; 
<span style="white-space:pre">	</span>return row; 
}


6.把plist文件中的数据赋给数组

NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];
 NSArray *array = [NSArray arrayWithContentsOfFile:path];


7.获取触摸的点

- (CGPoint)locationInView:(UIView *)view; 
- (CGPoint)previousLocationInView:(UIView *)view;


8.获取触摸的属性

@property(nonatomic,readonly) NSTimeInterval timestamp; 
@property(nonatomic,readonly) UITouchPhase phase; 
@property(nonatomic,readonly) NSUInteger tapCount;


9.从plist中获取数据赋给字典

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"plist"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath]; 


10.NSUserDefaults注意事项

设置完了以后如果存储的东西比较重要的话,一定要同步一下 
[[NSUserDefaults standardUserDefaults] synchronize];


11.获取Documents目录

NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

12.获取tmp目录

NSString *tmpPath = NSTemporaryDirectory();

13.利用Safari打开一个链接

NSURL *url = [NSURL URLWithString:@"http://baidu.com"]; 
[[UIApplication sharedApplication] openURL:url];


14.利用UIWebView显示pdf文件,网页等等

UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds]; 
webView.delegate = self; webView.scalesPageToFit = YES;
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
[webView setAllowsInlineMediaPlayback:YES]; 
[self.view addSubview:webView]; 
NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"pdf"]; NSURL *url = [NSURL fileURLWithPath:pdfPath]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:5]; 


15.UIWebView和html的简单交互

myWebView = [[UIWebView alloc]initWithFrame:self.view.bounds]; 
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]]; 
NSError *error; 
<span style="font-size:18px;">NSString *errorString = [NSString stringWithFormat:@"AnError Occurred;
%@</span><span style="font-family:Microsoft Yahei, Hiragino Sans GB, Helvetica, Helvetica Neue, 微软雅黑, Tahoma, Arial, sans-serif;color:#14191e;"><span style="font-size: 14px;">"<html><center><font size=+5 color='red'>AnError Occurred;<br>%@</font><.center><?html>"</span></span><span style="font-size:18px;">,error]; </span>
[myWebView loadHTMLString:errorString baseURL:nil]; 
//页面跳转了以后,停止载入 
-(void)viewWillDisappear:(BOOL)animated { 
<span style="white-space:pre">	</span>if (myWebView.isLoading) { 
<span style="white-space:pre">		</span>[myWebView stopLoading]; 
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span> myWebView.delegate = nil; 
<span style="white-space:pre">	</span>[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
}

16.汉字转码

NSString *oriString = @"\u67aa\u738b"; NSString *escapedString = [oriString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

17.处理键盘通知

- (void)keyboardWasShown:(NSNotification *)notification { 
<span style="white-space:pre">	</span>if (keyboardShown) { 
<span style="white-space:pre">		</span>return; 
<span style="white-space:pre">	</span>} 
<span style="white-space:pre">	</span>NSDictionary *info = [notification userInfo]; 
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; 
<span style="white-space:pre">	</span>CGSize keyboardSize = [aValue CGRectValue].size; 
<span style="white-space:pre">	</span>CGRect viewFrame = scrollView.frame; 
<span style="white-space:pre">	</span>viewFrame.size.height = keyboardSize.height; 
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>CGRect textFieldRect = activeField.frame; 
<span style="white-space:pre">	</span>[scrollView scrollRectToVisible:textFieldRect animated:YES]; keyboardShown = YES;
- (void)keyboardWasHidden:(NSNotification *)notification { 
<span style="white-space:pre">	</span>NSDictionary *info = [notification userInfo]; 
<span style="white-space:pre">	</span>NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; 
<span style="white-space:pre">	</span>CGSize keyboardSize = [aValue CGRectValue].size; 
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>CGRect viewFrame = scrollView.frame; 
<span style="white-space:pre">	</span>viewFrame.size.height += keyboardSize.height; 
<span style="white-space:pre">	</span>scrollView.frame = viewFrame; 
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>keyboardShown = NO; 
}

18.点击键盘的next按钮,在不同的textField之间换行

- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
<span style="white-space:pre">	</span>if ([textField returnKeyType] != UIReturnKeyDone) {
<span style="white-space:pre">		</span> NSInteger nextTag = [textField tag] + 1;
<span style="white-space:pre">		</span> UIView *nextTextField = [self.tableView viewWithTag:nextTag]; 
<span style="white-space:pre">		</span>[nextTextField becomeFirstResponder]; 
<span style="white-space:pre">	</span>}else { 
<span style="white-space:pre">	</span>[textField resignFirstResponder]; 
<span style="white-space:pre">	</span>} 
<span style="white-space:pre">	</span>return YES;
 }

19.设置日期格式

dateFormatter = [[NSDateFormatter alloc]init]; 
dateFormatter.locale = [NSLocale currentLocale]; 
dateFormatter.calendar = [NSCalendar autoupdatingCurrentCalendar]; 
dateFormatter.timeZone = [NSTimeZone defaultTimeZone]; 
dateFormatter.dateStyle = NSDateFormatterShortStyle; 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

20.加载大量图片的时候可以使用

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"]; 
UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];

21.有时候在iPhone游戏中,既要播放背景音乐,同时又要播放比如枪的开火音效

NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"xx" ofType:@"wav"];
NSURL *musicURL = [NSURL fileURLWithPath:musicFilePath]; 
AVAudioPlayer *musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:musicURL error:nil]; 
[musicPlayer prepareToPlay]; 
musicPlayer.volume = 1; 
musicPlayer.numberOfLoops = -1;//-1表示一直循环

22.从通讯录中读取电话号码,去掉数字之间的-

NSString *originalString = @"(123)123123abc"; 
NSMutableString *strippedString = [NSMutableString stringWithCapacity:originalString.length]; 
NSScanner *scanner = [NSScanner scannerWithString:originalString]; 
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; 
<span style="white-space:pre">	</span>while ([scanner isAtEnd] == NO) { 
<span style="white-space:pre">		</span>NSString *buffer; 
<span style="white-space:pre">		</span>if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) { 
<span style="white-space:pre">			</span>[strippedString appendString:buffer]; 
<span style="white-space:pre">		</span>}else { 
<span style="white-space:pre">			</span>scanner.scanLocation = [scanner scanLocation] + 1; 
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span> }
<span style="white-space:pre">	</span> NSLog(@"%@",strippedString);

23.正则判断:字符串只包含字母和数字

NSString *myString = @"Letter1234"; 
NSString *regex = @"[a-z][A-Z][0-9]"; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
<span style="white-space:pre">	</span> if ([predicate evaluateWithObject:myString]) { 
<span style="white-space:pre">		</span>//implement 
<span style="white-space:pre">	</span>}

24.设置UITableView的滚动条颜色

self.tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite; 

25.使用NSURLConnection下载数据

1. 创建对象 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]; 
[NSURLConnection connectionWithRequest:request delegate:self]; 
2. NSURLConnection delegate 委托方法 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
<span style="white-space:pre">	</span>//implement
<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { </span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span>//implement</span>
<span style="font-family: Arial, Helvetica, sans-serif;">} </span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;">- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span>//implement</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> }</span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> - (void)connectionDidFinishLoading:(NSURLConnection *)connection {</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span>//implement</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> }</span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> 3. 实现委托方法 </span>
<span style="font-family: Arial, Helvetica, sans-serif;">- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { </span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span>self.receiveData.length = 0;//先清空数据</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> }</span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span> [self.receiveData appendData:data]; </span>
<span style="font-family: Arial, Helvetica, sans-serif;">} </span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;">- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { </span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span>//错误处理 </span>
<span style="font-family: Arial, Helvetica, sans-serif;">} </span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;">- (void)connectionDidFinishLoading:(NSURLConnection *)connection { </span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span>[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; </span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span>NSString *returnString = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];</span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">	</span> firstTimeDownloaded = YES;</span>
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> } </span>


26.隐藏状态栏

[UIApplication sharedApplication].statusBarHidden = YES;

27..m和.mm文件的区别

.m文件是objective-c文件
.mm文件相当于c++或者c文件

28.读取一般性文件

- (void)readFromTXT {
<span style="white-space:pre">	</span> NSString *tmp;
<span style="white-space:pre">	</span> NSArray *lines;//将文件转化为一行一行的 
<span style="white-space:pre">	</span>lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"] componentsSeparatedByString:@"\n"]; 
<span style="white-space:pre">	</span>NSEnumerator *nse = [lines objectEnumerator]; //读取<>里的内容 
<span style="white-space:pre">	</span>while (tmp == [nse nextObject]) { 
<span style="white-space:pre">		</span>NSString *stringBetweenBrackets = nil; 
<span style="white-space:pre">		</span>NSScanner *scanner = [NSScanner scannerWithString:tmp];
<span style="white-space:pre">		</span>[scanner scanUpToString:@"<" intoString:nil]; 
<span style="white-space:pre">		</span>[scanner scanString:@"<" intoString:nil]; <span style="white-space:pre">	</span>
<span style="white-space:pre">		</span>[scanner scanUpToString:@">" intoString:&stringBetweenBrackets]; 
<span style="white-space:pre">		</span>NSLog(@"%@",[stringBetweenBrackets description]); 
<span style="white-space:pre">	</span>} 
}

29.隐藏UINavigationBar

[self.navigationController setNavigationBarHidden:YES animated:YES];

30.调用电话,短信,邮件

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:[email protected]?Subject=hello"]];
sms://调用短信 
tel://调用电话 
itms://打开MobileStore.app

31.获取版本信息

UIDevice *myDevice = [UIDevice currentDevice]; 
NSString *systemVersion = myDevice.systemVersion;

32.UIWebView的使用

webView.delegate = self; 
(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { 
<span style="white-space:pre">	</span>NSURL *url = request.URL; NSString *urlStirng = url.absoluteString; 
<span style="white-space:pre">	</span>NSLog(@"%@",urlStirng); 
<span style="white-space:pre">	</span>return YES; 
} 


33.NSNotificationCenter带参数发送
MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:moviePath]]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie]; [theMovie play];
- (void)myMovieFinishedCallback:(NSNotification *)aNotification { 
<span style="white-space:pre">	</span>MPMoviePlayerController *theMovie = [aNotification object]; 
<span style="white-space:pre">	</span>[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie]; 
}

34.延迟一段时间执行某个方法

[self performSelector:@selector(dismissModal) withObject:self afterDelay:1.0];

35.用NSDateFormatter调整时间格式代码

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; 
NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]]; 

36.UIView设置成为圆角

mainView.layer.cornerRadius = 6;
mainView.layer.masksToBounds = YES;


37.iPhone更改键盘右下角按键的type

SearchBar *mySearchBar = [[UISearchBar alloc]init]; 
mySearchBar.frame = CGRectMake(0, 0, self.view.bounds.size.width, 44);
mySearchBar.placeholder = @"placeholderString"; 
mySearchBar.delegate = self; 
[self.view addSubview:mySearchBar]; 
UITextField *searchField = [[mySearchBar subviews] lastObject]; 
searchField.returnKeyType = UIReturnKeyDone;



Objective-C内存管理

1.一个对象可以有一个或多个拥有者 
2.当它一个拥有者都没有的时候,它就会被回收 
3.如果想保留一个对象不被回收,你就必须成为它的拥有者 
 
 
关键字 
 
 
1.alloc 为对象分配内存,计数设为1,并返回此对象。 
2.copy 复制一个对象,此对象计数为1,返回此对象。你将成为此克隆对象的拥有者。 
3.retain 对象计数+1,并成为次对象的拥有者。 
4.release 对象计数-1,并丢掉此对象。 
5.autorelease 在未来的某一个时刻,对象计数-1。并在未来的某个时间放弃此对象。 
 
 
原则 
 
 
1.一个代码块内要确保copy,alloc 和 retain 的使用数量与 release 和 autorelease 的数量相等。 
2.在使用以 alloc 或 new 开头或包含 copy 的方法,或 retain 一个对象时,你将会编程它的拥有者。 
3.实现 dealloc 方法,这是系统当 retain -> 0 的时候,自动调用的。手动调用会引起 retain count 计数错误(多一次的 release)。

总结

不积跬步无以至千里,不积小流无以成江海   

  ———   与君共勉!











你可能感兴趣的:(UI,ios开发)