1.返回輸入鍵盤
`- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}`
2.CGRect
CGRectFromString(<#NSString *string#>)//有字符串恢復出矩形CGRectInset(<#CGRect rect#>, <#CGFloat dx#>, <#CGFloat dy#>)//創(chuàng)建較小或者較大的矩形CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)//判斷兩巨星是否交叉,是否重疊CGRectZero//高度和寬度為零的,位于(0邻悬,0)的矩形常量
3.隱藏狀態(tài)欄
###[UIApplicationsharedApplication]setStatusBarHidden:<#(BOOL)#> withAnimation:<#(UIStatusBarAnimation)#>//隱藏狀態(tài)欄
4.自動適應父視圖大小?
self.view.autoresizesSubviews=YES;self.view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
5.UITableView的一些方法
這里我自己做了個測試裸影,縮進級別設置為行號,row越大串前,縮進越多-(NSInteger)tableView:(UITableView*)tableView indentationLevelForRowAtIndexPath:(NSIndexPath*)indexPath{NSIntegerrow=indexPath.row;returnrow;}
6.把plist文件中的數(shù)據(jù)賦給數(shù)組
NSString*path=[[NSBundlemainBundle]pathForResource:@"States"ofType:@"plist"];NSArray*array=[NSArrayarrayWithContentsOfFile:path];
7.獲取觸摸的點
-(CGPoint)locationInView:(UIView*)view;-(CGPoint)previousLocationInView:(UIView*)view;
8.獲取觸摸的屬性
@property(nonatomic,readonly)NSTimeIntervaltimestamp;@property(nonatomic,readonly)UITouchPhasephase;@property(nonatomic,readonly)NSUIntegertapCount;
9.從plist中獲取數(shù)據(jù)賦給字典
NSString*plistPath=[[NSBundlemainBundle]pathForResource:@"book"ofType:@"plist"];NSDictionary*dictionary=[NSDictionarydictionaryWithContentsOfFile:plistPath];
10.NSUserDefaults注意事項
設置完了以后如果存儲的東西比較重要的話瘫里,一定要同步一下[[NSUserDefaultsstandardUserDefaults]synchronize];
11.獲取Documents目錄
NSString*documentsDirectory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
12.獲取tmp目錄
NSString*tmpPath=NSTemporaryDirectory();
13.利用Safari打開一個鏈接
NSURL*url=[NSURLURLWithString:@"http://baidu.com"];[[UIApplicationsharedApplication]openURL:url];
14.利用UIWebView顯示pdf文件,網(wǎng)頁等等
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=[[UIWebViewalloc]initWithFrame:self.view.bounds];[myWebView loadRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://www.baidu.com"]]];NSError*error;NSString*errorString=[NSStringstringWithFormat:@"AnError Occurred;
%@",error];[myWebView loadHTMLString:errorString baseURL:nil];//頁面跳轉了以后荡碾,停止載入-(void)viewWillDisappear:(BOOL)animated{if(myWebView.isLoading){[myWebView stopLoading];}myWebView.delegate=nil;[UIApplicationsharedApplication].networkActivityIndicatorVisible=NO;}
16.漢字轉碼
NSString*oriString=@"\u67aa\u738b";NSString*escapedString=[oriString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
17.處理鍵盤通知
先注冊通知谨读,然后實現(xiàn)具體當鍵盤彈出來要做什么,鍵盤收起來要做什么-(void)registerForKeyboardNotifications{keyboardShown=NO;//標記當前鍵盤是沒有顯示的[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWasShown:)name:UIKeyboardWillShowNotificationobject:nil];[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWasHidden:)name:UIKeyboardDidHideNotificationobject:nil];}//鍵盤顯示要做什么-(void)keyboardWasShown:(NSNotification*)notification{if(keyboardShown){return;}NSDictionary*info=[notification userInfo];NSValue*aValue=[info objectForKey:UIKeyboardFrameBeginUserInfoKey];CGSizekeyboardSize=[aValueCGRectValue].size;CGRectviewFrame=scrollView.frame;viewFrame.size.height=keyboardSize.height;CGRecttextFieldRect=activeField.frame;[scrollView scrollRectToVisible:textFieldRect animated:YES];keyboardShown=YES;}-(void)keyboardWasHidden:(NSNotification*)notification{NSDictionary*info=[notification userInfo];NSValue*aValue=[info objectForKey:UIKeyboardFrameEndUserInfoKey];CGSizekeyboardSize=[aValueCGRectValue].size;CGRectviewFrame=scrollView.frame;viewFrame.size.height+=keyboardSize.height;scrollView.frame=viewFrame;keyboardShown=NO;}
18.點擊鍵盤的next按鈕坛吁,在不同的textField之間換行
-(BOOL)textFieldShouldReturn:(UITextField*)textField{if([textField returnKeyType]!=UIReturnKeyDone){NSIntegernextTag=[textField tag]+1;UIView*nextTextField=[self.tableView viewWithTag:nextTag];[nextTextField becomeFirstResponder];}else{[textField resignFirstResponder];}returnYES;}
19.設置日期格式
dateFormatter=[[NSDateFormatteralloc]init];dateFormatter.locale=[NSLocalecurrentLocale];dateFormatter.calendar=[NSCalendarautoupdatingCurrentCalendar];dateFormatter.timeZone=[NSTimeZonedefaultTimeZone];dateFormatter.dateStyle=NSDateFormatterShortStyle;NSLog(@"%@",[dateFormatter stringFromDate:[NSDatedate]]);
20.加載大量圖片的時候劳殖,可以使用
NSString*imagePath=[[NSBundlemainBundle]pathForResource:@"icon"ofType:@"png"];UIImage*myImage=[UIImageimageWithContentsOfFile:imagePath];
21.有時候在iPhone游戲中,既要播放背景音樂拨脉,同時又要播放比如槍的開火音效哆姻。
NSString*musicFilePath=[[NSBundlemainBundle]pathForResource:@"xx"ofType:@"wav"];NSURL*musicURL=[NSURL fileURLWithPath:musicFilePath];AVAudioPlayer*musicPlayer=[[AVAudioPlayeralloc]initWithContentsOfURL:musicURL error:nil];[musicPlayer prepareToPlay];musicPlayer.volume=1;musicPlayer.numberOfLoops=-1;//-1表示一直循環(huán)
22.從通訊錄中讀取電話號碼,去掉數(shù)字之間的-
NSString*originalString=@"(123)123123abc";NSMutableString*strippedString=[NSMutableStringstringWithCapacity:originalString.length];NSScanner*scanner=[NSScannerscannerWithString:originalString];NSCharacterSet*numbers=[NSCharacterSetcharacterSetWithCharactersInString:@"0123456789"];while([scanner isAtEnd]==NO){NSString*buffer;if([scanner scanCharactersFromSet:numbers intoString:&buffer]){[strippedString appendString:buffer];}else{scanner.scanLocation=[scanner scanLocation]+1;}}NSLog(@"%@",strippedString);
23.正則判斷:字符串只包含字母和數(shù)字
NSString*myString=@"Letter1234";NSString*regex=@"[a-z][A-Z][0-9]";NSPredicate*predicate=[NSPredicatepredicateWithFormat:@"SELF MATCHES %@",regex];if([predicate evaluateWithObject:myString]){//implement}
24.設置UITableView的滾動條顏色
self.tableView.indicatorStyle=UIScrollViewIndicatorStyleWhite;
網(wǎng)絡編程 開發(fā)web等網(wǎng)絡應用程序的時候玫膀,需要確認網(wǎng)絡環(huán)境矛缨,連接情況等信息。如果沒有處理它們帖旨,是不會通過apple的審查的箕昭。 系統(tǒng)自帶的網(wǎng)絡檢查是原生的,AFNetworking也為我們添加了相關檢測機制碉就,所以這個直接在介紹AFNetworking的時候詳解吧盟广。
25.使用NSURLConnection下載數(shù)據(jù)
1.創(chuàng)建對象NSMutableURLRequest*request=[NSMutableURLRequestrequestWithURL:[NSURLURLWithString:@"http://www.baidu.com"]];[NSURLConnectionconnectionWithRequest:requestdelegate:self];2.NSURLConnectiondelegate委托方法-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{}-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{}-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{}-(void)connectionDidFinishLoading:(NSURLConnection*)connection{}3.實現(xiàn)委托方法-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{self.receiveData.length=0;//先清空數(shù)據(jù)}-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{[self.receiveData appendData:data];}-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{//錯誤處理}-(void)connectionDidFinishLoading:(NSURLConnection*)connection{[UIApplicationsharedApplication].networkActivityIndicatorVisible=NO;NSString*returnString=[[NSStringalloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];firstTimeDownloaded=YES;}
iOS的動畫以及自定義圖形,開個專欄總結瓮钥。
26.隱藏狀態(tài)欄
[UIApplicationsharedApplication].statusBarHidden=YES;
27..m文件與.mm文件的區(qū)別
.m文件是objective-c文件.mm文件相當于c++或者c文件
Safari其實沒有把內(nèi)存的緩存寫到存儲卡上
28.讀取一般性文件
-(void)readFromTXT{NSString*tmp;NSArray*lines;//將文件轉化為一行一行的lines=[[NSStringstringWithContentsOfFile:@"testFileReadLines.txt"]componentsSeparatedByString:@"\n"];NSEnumerator*nse=[lines objectEnumerator];//讀取<>里的內(nèi)容while(tmp==[nse nextObject]){NSString*stringBetweenBrackets=nil;NSScanner*scanner=[NSScannerscannerWithString:tmp];[scanner scanUpToString:@"<"intoString:nil];[scanner scanString:@"<"intoString:nil];[scanner scanUpToString:@">"intoString:&stringBetweenBrackets];NSLog(@"%@",[stringBetweenBrackets description]);}}
29.隱藏UINavigationBar
[self.navigationController setNavigationBarHidden:YES animated:YES];
30.調(diào)用電話筋量,短信,郵件
[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"mailto:apple@mac.com?Subject=hello"]];sms://調(diào)用短信tel://調(diào)用電話itms://打開MobileStore.app
31.獲取版本信息
UIDevice*myDevice=[UIDevicecurrentDevice];NSString*systemVersion=myDevice.systemVersion;
32.UIWebView的使用
webView.delegate = self;
(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = request.URL;
NSString *urlStirng = url.absoluteString;
NSLog(@"%@",urlStirng);
return YES;
}
UIButton的title和image不能同時顯示UINavigationItem也是
33.NSNotificationCenter帶參數(shù)發(fā)送
MPMoviePlayerController*theMovie=[[MPMoviePlayerControlleralloc]initWithContentURL:[NSURL fileURLWithPath:moviePath]];[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(myMovieFinishedCallback:)name:MPMoviePlayerPlaybackDidFinishNotificationobject:theMovie];[theMovie play];-(void)myMovieFinishedCallback:(NSNotification*)aNotification{MPMoviePlayerController*theMovie=[aNotificationobject];[[NSNotificationCenterdefaultCenter]removeObserver:selfname:MPMoviePlayerPlaybackDidFinishNotificationobject:theMovie];}
34.延遲一段時間執(zhí)行某個函數(shù)
[selfperformSelector:@selector(dismissModal)withObject:selfafterDelay:1.0];
35.用NSDateFormatter調(diào)整時間格式代碼
NSDateFormatter*dateFormatter=[[NSDateFormatteralloc]init];dateFormatter.dateFormat=@"yyyy-MM-dd HH:mm:ss";NSString*currentDateStr=[dateFormatter stringFromDate:[NSDatedate]];
36.UIView設置成圓角的方法
mainView.layer.cornerRadius=6;mainView.layer.masksToBounds=YES;
Objective-C 內(nèi)存管理
一個對象可以有一個或多個擁有者
當它一個擁有者都沒有的時候碉熄,它就會被回收
如果想保留一個對象不被回收桨武,你就必須成為它的擁有者
關鍵字
alloc 為對象分配內(nèi)存,計數(shù)設為1锈津,并返回此對象呀酸。
copy 復制一個對象,此對象計數(shù)為1琼梆,返回此對象性誉。你將成為此克隆對象的擁有者。
retain 對象計數(shù)+1茎杂,并成為次對象的擁有者错览。
release 對象計數(shù)-1,并丟掉此對象煌往。
autorelease 在未來的某一個時刻倾哺,對象計數(shù)-1。并在未來的某個時間放棄此對象。
原則
一個代碼塊內(nèi)要確保copy羞海,alloc 和 retain 的使用數(shù)量與 release 和 autorelease 的數(shù)量相等忌愚。
在使用以 alloc 或 new 開頭或包含 copy 的方法,或 retain 一個對象時却邓,你將會編程它的擁有者硕糊。
實現(xiàn) dealloc 方法,這是系統(tǒng)當 retain -> 0 的時候申尤,自動調(diào)用的癌幕。手動調(diào)用會引起 retain count 計數(shù)錯誤(多一次的 release)。
iPhone 更改鍵盤右下角按鍵的 type
SearchBar*mySearchBar=[[UISearchBaralloc]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;
總結
不積跬步無以至千里昧穿,不積小流無以成江海。