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)。

總結

不積跬步無以至千里,不積小流無以成江海   

  ———   與君共勉!











發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章