1.不可變數(shù)組轉(zhuǎn)變?yōu)榭勺償?shù)組聲明實(shí)例變量的數(shù)組? 必須記得實(shí)現(xiàn)
對(duì)于遍歷數(shù)組找到對(duì)象后 如果還需要查找 記得先結(jié)束 再查找(return/break)
NSArray * arr = @[@"人在囧途",@"煎餅俠",@"西游記",];
NSMutableArray *? arr = [NSMutableArrayarrayWithArray:arr];
在數(shù)組中取數(shù)據(jù)的時(shí)候? 需要通過后綴 將數(shù)組中的對(duì)象轉(zhuǎn)化為數(shù)字類
p11.age=
[newArr[1]intValue];
2.獲取字符串長(zhǎng)度NSString * str = nameLabel .text;
CGSizesize=
[strsizeWithAttributes:@{NSFontAttributeName: [UIFontsystemFontOfSize:17]}];
此時(shí)即可得到size
.width(字符串的寬? 即 字符串長(zhǎng)度)
3.將單獨(dú)的某個(gè)視圖上的視圖控制器的導(dǎo)航條隱藏
[objc]view plaincopy
-(void)viewDidAppear:(BOOL)animated{
[superviewDidAppear:animated?==NO];
[self.navigationControllersetNavigationBarHidden:YES];
}
4. 邊帽法 (拉伸圖片) 將某一像素點(diǎn)兒不斷地復(fù)制? 其他像素點(diǎn)不變 拉伸之后不會(huì)是圖片變形
[objc]view plaincopy
//第一種
[[UIImageViewalloc]init].image=?[[UIImageimageNamed:@"bubble.png"]stretchableImageWithLeftCapWidth:20topCapHeight:20];
//第二種
UIImage*?image?=[UIImageimageNamed:@"7.jpg"];
[imageresizableImageWithCapInsets:UIEdgeInsetsMake(0,?image.size.width,0,0)];
[[UIImageViewalloc]init].image=?image;
5. 監(jiān)聽系統(tǒng)發(fā)送的通知
[objc]view plaincopy
//??監(jiān)聽鍵盤frame發(fā)生變化的通知??并可以通過鍵盤的屬性獲得對(duì)象
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(KeyboardWillChangeFrame:)name:UIKeyboardWillChangeFrameNotificationobject:nil];
-?(void)KeyboardWillChangeFrame:(NSNotification*)noti?{
//????????UIKeyboardAnimationCurveUserInfoKey?=?7;
//????????UIKeyboardAnimationDurationUserInfoKey?=?"0.25";
//????????UIKeyboardBoundsUserInfoKey?=?"NSRect:?{{0,?0},?{320,?216}}";
//????????UIKeyboardCenterBeginUserInfoKey?=?"NSPoint:?{160,?588}";
//????????UIKeyboardCenterEndUserInfoKey?=?"NSPoint:?{160,?372}";
//????????UIKeyboardFrameBeginUserInfoKey?=?"NSRect:?{{0,?480},?{320,?216}}";
//????????UIKeyboardFrameChangedByUserInteraction?=?0;
//????????UIKeyboardFrameEndUserInfoKey?=?"NSRect:?{{0,?264},?{320,?216}}";
//一旦鍵盤發(fā)生改變的時(shí)候??_inputView??和??_tableView?的坐標(biāo)都要發(fā)生改變
//通過字典?獲取對(duì)象
NSDictionary*?dic?=?noti.userInfo;
//獲取動(dòng)畫時(shí)長(zhǎng)
floattime?=?[[dicobjectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];
//獲取動(dòng)畫速率
intcurve?=?[[dicobjectForKey:UIKeyboardAnimationCurveUserInfoKey]intValue];
//獲取鍵盤坐標(biāo)
CGRect?rect?=?[[dicobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
}
6.通過字符串繪制矩形? MAXFLOAT 無限
[objc]view plaincopy
NSString*?str?=?_chatArr[indexPath.row];
CGRect?rect?=?[strboundingRectWithSize:CGSizeMake(200,?MAXFLOAT)options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeadingattributes:@{NSFontAttributeName:?[UIFontsystemFontOfSize:15]}context:nil];
7.視圖層級(jí)切換
關(guān)鍵點(diǎn):
[self .window exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
1.如果父視圖不可交互? 那么放在其上邊的子視圖也不可交互
2. 如果父視圖可以交互? 那么放在上邊的子視圖的可交互性由自己決定
關(guān)鍵詞 :userInteractionEnabledimage .userInteractionEnabled=YES;
8.二進(jìn)制數(shù)據(jù)轉(zhuǎn)變類型
字符串轉(zhuǎn)變?yōu)槎M(jìn)制數(shù)據(jù)
NSString * str = @"girls";
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
二進(jìn)制數(shù)據(jù)轉(zhuǎn)變?yōu)樽址?/p>
NSString * str2 =[[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];
將圖片轉(zhuǎn)變?yōu)槎M(jìn)制數(shù)據(jù)
1.需要獲得圖片路徑
NSString * imageViewPath =[[NSBundle mainBundle]pathForResource:@"18" ofType:@"jpg"];
NSData * data = [[NSData alloc]initWithContentsOfFile:imageViewPath];
2.直接將添加在工程中的圖片轉(zhuǎn)化為二進(jìn)制數(shù)據(jù)類型
UIImage*
image = [UIImageimageNamed:@"20.jpg"];
NSData*
data =UIImageJPEGRepresentation(image,1);
將轉(zhuǎn)變?yōu)槎M(jìn)制數(shù)據(jù)的圖片轉(zhuǎn)變回圖片
方法1 ? 可以直接調(diào)用 從路徑中取出圖片
UIImage * image = [UIImage imageWithContentsOfFile:dataPath];
方法2 : 先將路徑中的二進(jìn)制數(shù)據(jù)取出? 然后 通過ImageWithData 屬性轉(zhuǎn)變?yōu)閳D片類型
NSData * data = [NSData dataWithContentsOfFile:[self getFilePath:@"data.plist"]];
UIImage * image =[UIImage imageWithData:data];
9.如何刪除一個(gè)視圖上的所有子視圖? 所有代碼:
獲取視圖上存放的所有子視圖? 遍歷數(shù)組 找到所有對(duì)象 找到 views
[objc]view plaincopy
for(UIView*?v?inself.view.subviews)?{
[vremoveFromSuperview];
}
10.將某個(gè)視圖放在最前邊
[self .view bringSubviewToFront:_tableView];
11.頁面跳轉(zhuǎn)(需要找window)
//找window
方法1:
[objc]view plaincopy
UIWindow*?window?=[[[UIApplicationsharedApplication]delegate]window];
window.rootViewController=?aViewController;
方法2:
[objc]view plaincopy
UIApplication*?app?=?[UIApplicationsharedApplication];
AppDelegate*?delegate?=?app.delegate;
UIWindow*?window?=?delegate.window;
window.rootViewController=?aViewController;
1.頁面翻轉(zhuǎn)
[objc]view plaincopy
[UIViewbeginAnimations:nilcontext:nil];
[UIViewsetAnimationDuration:1];
[UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUpforView:windowcache:YES];
[UIViewcommitAnimations];
2. 模態(tài)彈出? (present? 展示 ??? dismiss? 消失 )
3. 導(dǎo)航控制器? (push? 壓棧 ? pop? 出棧 )
//通過導(dǎo)航控制器控制視圖切換的時(shí)候
1. 返回上一界面:
[self.navigationControllerpopViewControllerAnimated:YES];
2. 返回根視圖控制器:
[self.navigationControllerpopToRootViewControllerAnimated:YES];
3.返回指定視圖:
//首先獲取目前所有的視圖控制器對(duì)象
NSArray*
arr? =self.navigationController.viewControllers;
//從數(shù)組中找到需要返回的根視圖
FirestViewController*
first = arr[0];
//返回指定視圖:
[self.navigationControllerpopToViewController:firstanimated:YES];
12.將數(shù)據(jù)庫文件拷貝到沙盒中
[objc]view plaincopy
//首先需要獲取數(shù)據(jù)庫文件的路徑??還有文件夾路徑
NSString*?sourePath?=?[[NSBundlemainBundle]pathForResource:@"database"ofType:@"sqlite"];
if(![[NSFileManagerdefaultManager]fileExistsAtPath:@"文件路徑"])?{
NSError*?error?=nil;
if(?[[NSFileManagerdefaultManager]copyItemAtPath:sourePathtoPath:@"文件路徑"error:&error])?{
NSLog(@"copy成功");
}
}
13:直接進(jìn)入網(wǎng)頁
[objc]view plaincopy
//網(wǎng)頁加載?:
//?創(chuàng)建url???NSURL:?NSObject????用來表示資源在互聯(lián)網(wǎng)的位置
NSURL??*?url?=??[NSURLURLWithString:@"http://www.baidu.com"];
//創(chuàng)建一個(gè)請(qǐng)求
NSURLRequest*request?=?[NSURLRequestrequestWithURL:url];
//加載請(qǐng)求
[webViewloadRequest:request];
[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"http//www.baidu.com"]];
14:將結(jié)構(gòu)體轉(zhuǎn)換成字符串再輸出
NSLog(@"-------%@",NSStringFromCGRect(rect));
15:角度轉(zhuǎn)弧度
可以定義為宏#define
ANGLE_2_HUDU(X) (X)*M_PI/180.0
計(jì)算圓形軌跡上控件的中心點(diǎn)坐標(biāo)時(shí)
中心點(diǎn) ?圓的半徑 ? ?角度轉(zhuǎn)弧度 ? ? ? 角度值
floatx
= 160 + 100 *cos(ANGLE_2_HUDU(btn.angle));
floaty
= 240 + 100 *sin(ANGLE_2_HUDU(btn
.angle));
//x = 中心點(diǎn)x + 半徑 * cos@
//y = 中心點(diǎn)y + 半徑 *sin@
16:交叉導(dǎo)入
//為了防止交叉導(dǎo)入
@class 文件
//只是告訴了編譯器有這個(gè)類? 但是該類的.h文件中有什么東西 編譯器是不知道的 ? 當(dāng)真正需要使用這個(gè)類的時(shí)候 還必須在.m 文件中導(dǎo)入#import
"TwoViewController.h”這個(gè)頭文件
17: center + bounds = frame ;
//center(設(shè)置中心點(diǎn))
+ bounds(設(shè)置寬.高) = frame
image .center = CGPointMake(160, 120);
//bounds (x,y ,width ,height ), 給bounds設(shè)置x和y是沒有作用的
image .bounds = CGRectMake(0, 0, 160, 120);
18:查詢父視圖
NSLog(@"==%@",image.superview);
查看view的子視圖
NSLog(@"==%@",self .window .subviews);
19.重新添加xib文件
如果創(chuàng)建的xib 文件的名字不同? 需要在入口方法中調(diào)用一下方法
ViewController * vc = [[ViewController alloc]initWithNibName:@"Empty" bundle:nil];
20.屏幕獲取觸摸對(duì)象
[objc]view plaincopy
-(void)touchesMoved:(NSSet*)toucheswithEvent:(UIEvent*)event?{
//獲取觸摸對(duì)象
UITouch*?touch?=[touchesanyObject];
//獲取觸摸對(duì)象?在某一視圖上的一個(gè)點(diǎn)
CGPoint?point?=?[touchlocationInView:self.view];
//把結(jié)構(gòu)體轉(zhuǎn)換為字符串輸出
NSLog(@"---%@",NSStringFromCGPoint(point));
//CGRectContainsPoint??作用??:?判斷CGRect???數(shù)據(jù)是否包含一個(gè)點(diǎn)?point?如果包含這個(gè)點(diǎn)?函數(shù)值就是1
//類似屬性?CGRectIntersectsRect(CGRect?rect1,?CGRect?rect2)?判斷兩個(gè)坐標(biāo)是否有交集
//NO1.?觸摸對(duì)象坐標(biāo)??NO2.結(jié)構(gòu)體
if(CGRectContainsPoint(self.view.frame,?point))?{
self.view.center=?point;
}
}
21:判斷對(duì)象之間聯(lián)系常用的屬性
1.判斷某個(gè)對(duì)象坐標(biāo)時(shí)候包含某個(gè)點(diǎn)
CGRectContainsPoint(self.frame.frame, point)
2. 判斷兩個(gè)坐標(biāo)是否有交集
CGRectIntersectsRect(rect1, ?rect2)
3.判斷兩個(gè)對(duì)象時(shí)候相等的時(shí)候
isEqualToString:
4. 判斷字符串類型數(shù)據(jù)長(zhǎng)度的時(shí)候 需要調(diào)用length
22.獲取系統(tǒng)當(dāng)前時(shí)間
[objc]view plaincopy
NSDate*?date?=?[NSDatedate];
//時(shí)間格式?年yyyy?月?MM?日dd?小時(shí)?HH?分鐘?mm?秒?ss
NSDateFormatter*?formatter??=?[[NSDateFormatteralloc]init];
[formattersetDateFormat:@"yy-MM-dd?HH-mm-ss"];
NSString*str?=?[formatterstringFromDate:date];
NSLog(@"-=-=-=-=-=-=-===%@",str);
23. 分割(返回值類型 - 數(shù)組)? . 拼接字符串
//分割:
NSArray * arr =[str componentsSeparatedByString:@" "];
//字符串之間用什么隔開 分割時(shí)? 在@“” 中就調(diào)用什么 (eg: |? 空格 等);
//拼接:
[NSString stringWithString:@""]
[NSString stringWithFormat:@""]
去掉字符串中間的空格
return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
去掉字符串的換行符
str =[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
24 .定時(shí)器 .延遲加載
//定時(shí)器開啟的時(shí)候 為防止點(diǎn)擊按鈕時(shí)開啟多個(gè)定時(shí)器造成混亂? 所以在開啟定時(shí)器的時(shí)候可以先判斷時(shí)候有開啟定時(shí)器
方法1:
[objc]view plaincopy
staticBOOLisOk;
if(isOk?==NO)?{
NSTimer*?timer?=??[NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(onTimer)userInfo:nilrepeats:YES];
//開啟定時(shí)器后?如果想要定時(shí)器立即開啟?可以調(diào)用
[timerfire];
isOk?=YES;
}
方法2 :
[objc]view plaincopy
if(_timer)?{
return;
}
_timer?=??[NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(onTimer)userInfo:nilrepeats:YES];
//關(guān)閉定時(shí)器時(shí)??記得立即將其指為空
[_timerinvalidate];
_timer?=nil;
延時(shí)加載
[objc]view plaincopy
//定時(shí)器綁定方法的時(shí)候??只能講自身傳過來
_timer?=?[NSTimerscheduledTimerWithTimeInterval:0.05target:selfselector:@selector(onTimer:)userInfo:?buttonrepeats:YES];
-(void)onTimer:?(NSTimer*)aTimer{
//通過userInfo?獲取點(diǎn)擊的按鈕
UIButton*?clickBtn?=?aTimer.userInfo;
}
//延遲加載?要點(diǎn)??需要調(diào)用performSelector
[selfperformSelector:@selector()withObject:nilafterDelay:5];
25 .文本框結(jié)束編輯的時(shí)候? 讓鍵盤下去
[objc]view plaincopy
-(void)touchesBegan:(NSSet*)toucheswithEvent:(UIEvent*)event{
[self.windowendEditing:YES];
}
26:向相冊(cè)中保存圖片
[objc]view plaincopy
UIImageWriteToSavedPhotosAlbum([UIImageimageNamed:@"20.jpg"],self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);
//必要實(shí)現(xiàn)的協(xié)議方法,?不然會(huì)崩潰
-?(void)image:(UIImage*)imagedidFinishSavingWithError:(NSError*)errorcontextInfo:(voidvoid*)contextInfo?{
}
27.輸出當(dāng)前所在的方法名:
NSLog(@"-----%s---", __func__);
28.三目運(yùn)算符
條件 ?(執(zhí)行操作) : 其它操作
number = i <= 8 ?(i + 1) : 0? 解釋 : 當(dāng)i 小于等于8 時(shí)? 執(zhí)行 i+1 的操作? 否則? 執(zhí)行冒號(hào)后面的操作? 即 i = 0;
29.在數(shù)組中隨機(jī)取出數(shù)據(jù)
1) 首先先在數(shù)組中隨機(jī)出一個(gè)索引
int? random = arc4random()%numberArray .count;
2) 將取出的數(shù)據(jù)轉(zhuǎn)化為想要的類型
int number = [numberArray [random] intvalue];
3) 將取出的數(shù)據(jù)在數(shù)組中刪除 ? 以防止隨機(jī)重復(fù)
[numberArray removeObjectAtIndex : random];
30.視圖修剪 .透明度? 隱藏視圖 移除視圖 :
clip? 修剪? bounds 邊界
1.是否對(duì)視圖修剪
bigView .clipsToBounds=YES;
2.設(shè)置圓角半徑
bigView .layer.cornerRadius=
90;
bigView.layer.masksToBounds=YES;
3.透明度:
_view .alpha = 0;
4.移除視圖 :
[_view removeFromSuperview];
31: 字符串拼接輸出控件屬性值
NSLog(@"
= %@",NSStringFromCGRect(nav.navigationBar.frame));
32:第一響應(yīng):
1.打開程序時(shí)? 文本框處于編輯狀態(tài) 即? 第一響應(yīng)
成為第一響應(yīng) [_textfieldbecomeFirstResponder];
失去第一響應(yīng)[_textfield resignFirstResponder];
2.在tocubegin協(xié)議方法中調(diào)用
[self.view endEditing: YES]
33 .導(dǎo)航控制器相關(guān)控件內(nèi)容
1.設(shè)置導(dǎo)航條的背景顏色
錯(cuò)誤做法:nav
.navigationBar.backgroundColor=
[UIColorgrayColor];
正確做法:nav
.navigationBar.barTintColor=
[UIColorgrayColor];
2.設(shè)置導(dǎo)航條標(biāo)題self.title=@"導(dǎo)航條";
3. 設(shè)置左右欄按鈕項(xiàng) (記得按鈕綁定方法的實(shí)現(xiàn))
[objc]view plaincopy
UIBarButtonItem*?lifeItem?=?[[UIBarButtonItemalloc]initWithTitle:@"保存"style:UIBarButtonItemStylePlaintarget:selfaction:(@selector(baoCunBtnClick:))];
self.navigationItem.leftBarButtonItem=?lifeItem;
UIBarButtonItem*?rightItem?=?[[UIBarButtonItemalloc]initWithTitle:@"添加分組"style:UIBarButtonItemStylePlaintarget:selfaction:(@selector(addGrounpBtnClick:))];
self.navigationItem.rightBarButtonItem=?rightItem;
4.隱藏導(dǎo)航條 :
//注意: 隱藏導(dǎo)航條的時(shí)候 不能混著用 怎么讓導(dǎo)航條隱藏的 就怎么讓導(dǎo)航條出現(xiàn) :
方法1:
[self.navigationControllersetNavigationBarHidden:YES];
[self.navigationControllersetNavigationBarHidden:YESanimated:YES];
方法2:self.navigationController.navigationBarHidden=YES;
self.navigationController.navigationBarHidden=NO;
補(bǔ)充 :? 在視圖將要顯示的時(shí)候? 隱藏導(dǎo)航條 :
[objc]view plaincopy
-(void)viewWillAppear:(BOOL)animated?{
[superviewWillAppear:animated];
[self.navigationControllersetNavigationBarHidden:YES];
}
5.設(shè)置導(dǎo)航條按鈕項(xiàng)時(shí)候添加圖片? (圖片渲染)
[objc]view plaincopy
UIImage*?image?=?[[UIImageimageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIBarButtonItem*?backBar?=?[[UIBarButtonItemalloc]initWithImage:imagestyle:UIBarButtonItemStylePlaintarget:selfaction:@selector(backClick)];
self.navigationItem.leftBarButtonItem=?backBar;
self.navigationController.view.contentMode=?UIViewContentModeScaleAspectFit;//設(shè)置內(nèi)容樣式,通過保持長(zhǎng)寬比縮放內(nèi)容適應(yīng)視圖的大小,任何剩余的區(qū)域的視圖的界限是透明的
///按鈕設(shè)置背景圖片時(shí)?設(shè)置背景圖片大小?防止圖片變形
UIImage*?btnImg?=?[UIImageimageNamed:@"button_table"];
UIImage*?bbImg?=?[btnImgstretchableImageWithLeftCapWidth:100topCapHeight:100];
6. 隱藏導(dǎo)航條自定義的返回按鈕 :
self.navigationItem.hidesBackButton=YES;
7.導(dǎo)航條上添加控件
self.navigationItem.titleView = 控件對(duì)象;
34.彈框
iOS8以后推薦使用UIAlertController
樣式1: UIAlertView
[objc]view plaincopy
UIAlertView*alertView?=[[UIAlertViewalloc]initWithTitle:@"提示"message:@"新建聯(lián)系人"delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"確定",nilnil];
//彈框樣式?:(帶輸入框)
alertView.alertViewStyle=UIAlertViewStyleLoginAndPasswordInput;
UITextField*field1=[alertViewtextFieldAtIndex:0];
UITextField*field2=[alertViewtextFieldAtIndex:1];
field1.placeholder=@"請(qǐng)輸入姓名";
field2.placeholder=@"請(qǐng)輸入電話";
field2.secureTextEntry=NO;
[alertViewshow];
//實(shí)現(xiàn) alertView? 首先在.h文件中 實(shí)現(xiàn)協(xié)議
實(shí)現(xiàn)協(xié)議方法:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
//通過buttonIndex 的索引值 判斷點(diǎn)擊的是哪個(gè)按鈕? 0 ,1
樣式2:ActionSheet
//ActionSheet
不可以在viewDidLoad 方法中創(chuàng)建? 這是因?yàn)?ActionSheet 是在self .view 上展示的
此時(shí)我們的viewDidLoad 方法還沒有走完 ? 我們的self.view 就不能展示出來 self.view 還沒有展示
那么我們放在self.view上的actionsheet 也就無法展示
UIActionSheet*
actionSheet = [[UIActionSheetalloc]initWithTitle:@"提示"delegate:selfcancelButtonTitle:@"取消"destructiveButtonTitle:@"確定"otherButtonTitles:nil,nil];
[actionSheetshowInView:self.view];
7.設(shè)置cell的背景顏色
[objc]view plaincopy
-(void)tableView:(UITableView*)tableViewwillDisplayCell:(UITableViewCell*)cellforRowAtIndexPath:(NSIndexPath*)indexPath?{
[cellsetBackgroundColor:[UIColorblackColor]];
}
35.
九宮格
[objc]view plaincopy
//方法1:?嵌套for?循環(huán)
for(inta?=0;?a?<2;?a?++)?{
for(intb?=0;?b?<3;?b++)?{
UIButton*?btn?=?[UIButtonbuttonWithType:UIButtonTypeSystem];
btn.backgroundColor=?[UIColorredColor];
btn.frame=?CGRectMake(30+?(320-70)*a,80+?(60+40)?*?b,40,40);
[self.viewaddSubview:btn];
}
}
//方法2?.單個(gè)for循環(huán)
//?三行三列
for(inta?=0;??a?<9;?a?++)?{
floatjiange?=?(320-440*3)/4;
intx?=?a%3;
inty?=?a/3;
UIButton*?btn?=?[UIButtonbuttonWithType:UIButtonTypeSystem];
btn.backgroundColor=?[UIColorredColor];
btn.frame=CGRectMake(jiange?+?(40+?jiange)?*x,?jiange?+?(40+?jiange)?*?y,40,40);
}
36.直接在輸出中判斷布爾類型
n.sex?@"男鳥":@"女鳥"
37.服務(wù)器
- 去掉out.println --句中的ln換行符
str =[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
38.如果URL中路徑的字符串拼接的時(shí)候
有中文 需要編碼
NSString*encodingString
= [pathstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
39.獲取沙盒文件中某個(gè)文件夾下的所有內(nèi)容
contentsOfDirectoryAtPath
[objc]view plaincopy
NSString*filePath?=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];
//返回值類型是數(shù)組
NSArray*arr?=??[[NSFileManagerdefaultManager]contentsOfDirectoryAtPath:filePatherror:nil];
NSLog(@"arr===%@",arr);
40 .獲取沙盒文件中某個(gè)文件的屬性
[objc]view plaincopy
NSString*filePath?=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/str.plist"];
//返回值類型是字典??所以我們可以通過字典內(nèi)的鍵值??取出我們想要的數(shù)據(jù)
NSDictionary*dic?=?[[NSFileManagerdefaultManager]attributesOfItemAtPath:filePatherror:nil];
unsignedlonglongsize=?[dicfileSize];
NSLog(@"----%llu",size);
NSLog(@"dic====%@",dic);
41:輸出對(duì)象的時(shí)候設(shè)置輸出字符串格式調(diào)用的方法
[objc]view plaincopy
//輸出對(duì)象的時(shí)候?會(huì)調(diào)用該對(duì)象的description?方法
-(NSString*)description{
return[NSStringstringWithFormat:@"IP-----%p???name----%@???age-----%d",self,self.name,self.age];
}
42:沙盒文件中路徑查找的便捷方式
1.獲取根目錄文件路徑
NSLog(@"-----%@",NSHomeDirectory());
2.獲取臨時(shí)文件路徑方法類似于獲取根目錄文件路徑
NSString*
temp =NSTemporaryDirectory();
3.獲取資源包路徑
NSString*appPath =??? [[NSBundlemainBundle]bundlePath];
4.獲取某圖片或文件夾路徑
NSString * imageViewPath =[[NSBundle mainBundle]pathForResource:@"18" ofType:@"jpg"];
5.獲取某目錄下的文件—>文件路徑
NSDictionary * dic =[[NSFileManager defaultManager]attributesOfItemAtPath:[self getPath] error:nil];
43:對(duì)象序列化
歸檔步驟 :
1. 創(chuàng)建可變的data (相當(dāng)于一個(gè)空的袋子 )NSMutableData*
data= [[NSMutableDataalloc]initWithCapacity:0];
2.歸檔? 關(guān)鍵詞 : archiver
NSKeyedArchiver*
archiver = [[NSKeyedArchiveralloc]initForWritingWithMutableData:data];
3.編碼 : (就是將對(duì)象類轉(zhuǎn)變?yōu)槎M(jìn)制數(shù)據(jù)的過程)
[archiver encodeObject:_arr];
//如果有多個(gè)對(duì)象的時(shí)候 通過 設(shè)置 key值來區(qū)分
[archiverencodeObject:_arrforKey:@"arr"];
[archiverencodeObject:_viewforKey:@"view"];
4.結(jié)束編碼的時(shí)候? 必須調(diào)用 接收方法 (完成編碼)
[archiverfinishEncoding];
5.可以將轉(zhuǎn)變?yōu)槎M(jìn)制數(shù)據(jù)類型的 對(duì)象類寫入沙盒中
[datawriteToFile:
[selfgetFilePath]atomically:YES];
反序列化 (將二進(jìn)制數(shù)據(jù)類型 轉(zhuǎn)換為對(duì)象類)
1. 在沙盒中取出data數(shù)據(jù)
NSData*
data = [[NSDataalloc]initWithContentsOfFile:[selfgetFilePath]];
2.將取出的數(shù)據(jù)交給反序列化來讀
NSKeyedUnarchiver*
unarchiver = [[NSKeyedUnarchiveralloc]initForReadingWithData:data];
3.解碼
NSArray * arr =? [unarchiver decodeObject];
//如果有多個(gè)對(duì)象 (如上)
NSArray*
arr = [unarchiverdecodeObjectForKey:@"arr"];
4.結(jié)束解碼 :
[unarchiverfinishDecoding];
補(bǔ)充 :? 為了調(diào)取路徑方法方便? 可以將獲取路徑封裝成方法 便于調(diào)用
[objc]view plaincopy
-(NSString*)getFilePath{
return[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/arr.plist"];
}
2.自定義對(duì)象轉(zhuǎn)碼的時(shí)候
1. 需要在.h文件中必須實(shí)現(xiàn)的協(xié)議
2.在.m 文件中必須實(shí)現(xiàn)的兩個(gè)方法
//將people類中的屬性進(jìn)行編碼
//aCoder 編碼器
//當(dāng)用序列化器編碼對(duì)象的時(shí)候 , 該方法就會(huì)被調(diào)用
[objc]view plaincopy
-(void)encodeWithCoder:(NSCoder*)aCoder{
NSLog(@"3333333333");
[aCoderencodeObject:_nameforKey:@"name"];
[aCoderencodeInt:_ageforKey:@"age"];
}
//解碼
//aDecoder 解碼器
//反序列化時(shí) 將NSData 解碼成對(duì)象類型調(diào)用的方法
[objc]view plaincopy
-(id)initWithCoder:(NSCoder*)aDecoder?{
//任意類型??初始化[super?init]?方法
self=?[superinit];
if(self)?{
//需要self.屬性??接收
self.name=?[aDecoderdecodeObjectForKey:@"name"];
self.age=?[aDecoderdecodeIntForKey:@"age"];
}
returnself;
}
補(bǔ)充 :? 如果再創(chuàng)建一個(gè)類? 繼承與自定義people類時(shí)
實(shí)現(xiàn)第二個(gè)協(xié)議方法時(shí) (返回值為id 的協(xié)議方法? ) 需要先繼承父類方法 即:
[objc]view plaincopy
-(id)initWithCoder:(NSCoder*)aDecoder?{
self=?[superinitWithCoder:aDecoder];
if(self)?{
[aDecoderdecodeObjectForKey:@"huzi"];
}
returnself;
}
快速轉(zhuǎn)碼? :
1.直接將對(duì)象放在沙盒中
[NSKeyedArchiverarchiveRootObject:_arrtoFile:[selfgetFilePath]];
2. 在反序列化中直接取出對(duì)象
NSArray*
arr = [NSKeyedUnarchiverunarchiveObjectWithFile:[selfgetFilePath]];
44:NSUserDefaults儲(chǔ)存數(shù)據(jù)
(儲(chǔ)存輕量級(jí)的數(shù)據(jù)(賬號(hào) 密碼? 是否登錄))
//1.NSUserDefaults 可以存儲(chǔ)的數(shù)據(jù)類型 : NSString? 字典? 數(shù)組? NSNumber BOOL NSData(二進(jìn)制數(shù)據(jù)) NSDate(時(shí)間) int(integer)? Double ? float, URL(網(wǎng)址)
//2.強(qiáng)制數(shù)據(jù)及時(shí)存儲(chǔ)到沙盒
//userDefaults向沙盒中儲(chǔ)存數(shù)據(jù)是按照一定的時(shí)間戳定時(shí)儲(chǔ)存數(shù)據(jù)如果數(shù)據(jù)還沒來得及存儲(chǔ)而此時(shí)程序出現(xiàn)問題那么數(shù)據(jù)就會(huì)丟失所以我們可以同步一下強(qiáng)制數(shù)據(jù)及時(shí)存儲(chǔ)到沙盒
//synchronize同步保證數(shù)據(jù)及時(shí)的儲(chǔ)存到沙盒中
[userDefaults synchronize];
45: NSUserDefaults存取文件
[objc]view plaincopy
//存數(shù)據(jù):
[[NSUserDefaultsstandardUserDefaults]setObject:_nameField.textforKey:@"name"];
[[NSUserDefaultsstandardUserDefaults]setObject:_pswField.textforKey:@"psw"];
//同步數(shù)據(jù)
[[NSUserDefaultsstandardUserDefaults]synchronize];
//取數(shù)據(jù):
NSString*?nameString?=??[[NSUserDefaultsstandardUserDefaults]objectForKey:@"name"];
NSString*?pswString??=[[NSUserDefaultsstandardUserDefaults]objectForKey:@"psw"];
46:判斷某路徑下是否存在文件
是不是文件夾??? 關(guān)鍵詞 :fileExistsAtPath
[objc]view plaincopy
NSString*filePath1=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/str.plist"];
NSString*filePath2=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/ABC"];
BOOLisDirectory?;
BOOLisExist=?[[NSFileManagerdefaultManager]fileExistsAtPath:filePath2isDirectory:&isDirectory];
if(isExist==YES)?{
NSLog(@"存在文件");
if(isDirectory==YES)?{
NSLog(@"是個(gè)文件夾");
}else{
NSLog(@"不是文件夾");
}
}else{
NSLog(@"不存在文件");
}
47 .網(wǎng)絡(luò)請(qǐng)求中網(wǎng)絡(luò)超時(shí)設(shè)置request .timeoutInterval = 10;
48.單元格關(guān)鍵控件摘要
1.分割線顏色樣式:
tableVew .separatorColor=[UIColorredColor];
tableVew .separatorStyle=UITableViewCellSeparatorStyleNone;
2.單元格背景View
可以設(shè)置圖片 下拉的時(shí)候顯示
tableVew .backgroundView=imageView;
3.單元格表頭背景View可以設(shè)置圖片因?yàn)樾枰O(shè)置坐標(biāo)可以通過封裝方法然后在ViewDidLoad
方法中調(diào)用
tableVew.tableHeaderView=imageView;
4.視圖修剪
cell.imageView.layer.cornerRadius=50;
cell.imageView.layer.masksToBounds=YES;
5.cell小掛件
cell .accessoryType=UITableViewCellAccessoryDetailButton;
6.點(diǎn)擊單元格時(shí)候的樣式:
cell .selectionStyle=UITableViewCellSelectionStyleNone;
7.如果想把單元格的白色背景去掉的話
需要將tableView 和cell 上的背景顏色都設(shè)置為clearColor
8.點(diǎn)擊單元格上的按鈕時(shí)候在按鈕綁定的方法中找到點(diǎn)擊的是哪一行上的按鈕需要通過按鈕找到cell? 再通過cell 找到IndexPath
eg:UITableViewCell*
cell =(UITableViewCell*)btn.superview.superview;NSIndexPath*
indexPath =[_tableViewindexPathForCell:cell];
9.區(qū)頭區(qū)尾相關(guān)內(nèi)容
//也需要重用區(qū)頭和區(qū)尾的設(shè)置中 相關(guān)的控件設(shè)置和添加需要放在cell.contentView
e.g:
1.cell.contentView.backgroundColor=
[UIColorgrayColor];
2.[cell.contentViewaddSubview:img];
10.單元格索引:
將索引標(biāo)示放在數(shù)組中
self.arr=
@[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",];索引調(diào)用的方法:
[objc]view plaincopy
-(NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView?{
return_arr;
}
49. btn按鈕的失去響應(yīng)
btn .enabled = NO;
//默認(rèn)值 YES
btn.enabled = YES;
50.在為URL添加字符串時(shí)
包含特殊字符或中文的 需要編碼轉(zhuǎn)換
string =[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
51.圖片轉(zhuǎn)化為二進(jìn)制數(shù)據(jù)
//兩種方法都可以 但是 PNG的返回的圖片量與原圖大小差不多 而jpg 的會(huì)壓縮參數(shù)NSData * data = UIImagePNGRepresentation(self.imageView.image);
NSData * data = UIImageJPEGRepresentation(self.imageView.image, 0.1);
52.斷點(diǎn)下載個(gè)別屬性摘要
1. 獲取已經(jīng)下載文件的大小 文件較大的時(shí)候 可以用long long 創(chuàng)建實(shí)例變量
_receiveSize =[dic fileSize];
2.通過Range
頭 —> 可以指定每次從網(wǎng)上下載數(shù)據(jù)包的大小
[request addValue:[NSString stringWithFormat:@"bytes=%lld-",_receiveSize] forHTTPHeaderField:@"Range"];
3.期望從服務(wù)器中返回的剩余的數(shù)據(jù)expectedContentLength
long long lastSize = response.expectedContentLength;
4.受到響應(yīng)的時(shí)候
需要?jiǎng)?chuàng)建對(duì)象 并給對(duì)象一個(gè)寫文件的路徑
_fileHandle =? [NSFileHandle fileHandleForWritingAtPath:[self getPath]];
//找到已經(jīng)下載文件的結(jié)尾數(shù)據(jù)[_fileHandle seekToEndOfFile];
//寫入數(shù)據(jù)
[_fileHandle writeData:data];
//開始在接受數(shù)據(jù)的協(xié)議方法中不斷的追加數(shù)據(jù)
_receiveSize +=[data length];
5.下載進(jìn)度賦值到進(jìn)度條
//當(dāng)前下載比例=接收數(shù)據(jù)/總數(shù)據(jù)
float progress =(float) _receiveSize /_totalSize;
self.weak.progress = progress;
self .persentLabel.text = [NSString stringWithFormat:@"%.2f%%",progress*100];
6.暫停數(shù)據(jù)綁定的方法中
暫停請(qǐng)求數(shù)據(jù) 同時(shí)將請(qǐng)求數(shù)據(jù)指為空 (類似于定時(shí)器)
[_connection cancel];
_connection = nil;
53.OC中對(duì)用戶名和密碼編碼和加密常用的方法base64 MD5
//在需要加密內(nèi)容的后面添加后綴
[_nameField.textbase64EncodedString]編碼
[_nameField.textbase64DecodedString]解碼
[_pswField.textMD5]加密
54.在web請(qǐng)求體重? 截取某個(gè)字段
@"https://api.weibo.com/oauth2/authorize?client_id=1950801855&response_type=code&redirect_uri=http://www.baidu.com"該請(qǐng)求體中的code
NSRangerange
=[request.URL.absoluteStringrangeOfString:@"code="];
NSString*
code =[[request.URL.absoluteStringcomponentsSeparatedByString:@"="]lastObject];
都是單純地字符串操作
55.判斷授權(quán)token
和 過期時(shí)間的兩種方式 :
[objc]view plaincopy
//方式1:
NSString*?token?=[[NSUserDefaultsstandardUserDefaults]objectForKey:@"token"];
NSDate*?time?=[[NSUserDefaultsstandardUserDefaults]objectForKey:@"time"];
if(token?==nil||?[tokenisEqualToString:@""])?{
returnNO;
}
if([[NSDatedate]compare:time]?!=?NSOrderedAscending)?{
returnNO;
}
returnYES;
//方式2:
NSString*?token?=?[[NSUserDefaultsstandardUserDefaults]objectForKey:@"token"];
//過期時(shí)間
NSDate*?date?=?[[NSUserDefaultsstandardUserDefaults]objectForKey:@"date"];
if(token?==nil||?[tokenisEqualToString:@""])?{
returnNO;
}
//當(dāng)前時(shí)間
NSDate*?currentDate?=[NSDatedate];
//當(dāng)前時(shí)間和過期時(shí)間?對(duì)比
if([[currentDatelaterDate:date]isEqualToDate:currentDate])?{
returnNO;
}
returnYES;
56.如果需要設(shè)置多個(gè)tag值時(shí)
//一般設(shè)置tag值只需要設(shè)置為數(shù)字進(jìn)行區(qū)分的話 就可以 但是如果接口較多 需要區(qū)分的話 單獨(dú)的設(shè)置為數(shù)字 時(shí)間久的話 不好辨認(rèn) 所以我們可以模仿系統(tǒng)? 來寫出一個(gè)枚舉來
// NSInteger指的是枚舉中值的類型RequestType總的請(qǐng)求類型
typedefNS_ENUM(NSInteger, RequestType) {
GetTokenRequestTag = 0,
GetStatusListRequestTag
//需要再往下寫的時(shí)候? 不需要設(shè)置數(shù)字就可以 因?yàn)橄到y(tǒng)會(huì)自動(dòng)遞增
};
調(diào)用時(shí):view.tag =GetTokenRequestTag;
57.向上取整
[objc]view plaincopy
//首先可以先獲取矩形高度?然后向上取整
CGRect?rect?=[stringboundingRectWithSize:CGSizeMake(310,?MAXFLOAT)options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeadingattributes:@{NSFontAttributeName:?[UIFontsystemFontOfSize:17]}context:nil];
//向上取整
returnceilf(rect.size.height);
58.查找某個(gè)具體文件(eg:圖片)路徑的方法
[objc]view plaincopy
NSString*?directoryPath?=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/ImageCache"];
//保證沙盒中的Documents?中一定有一個(gè)ImageCache?文件夾
if(![[NSFileManagerdefaultManager]fileExistsAtPath:directoryPath])?{
[[NSFileManagerdefaultManager]createDirectoryAtPath:directoryPathwithIntermediateDirectories:YESattributes:nilerror:nil];
}
//把圖片的地址字符串分割?最后一個(gè)/?之后的那段就是圖片的名字
NSString*?fileName?=[[@"URLString"componentsSeparatedByString:@"/"]lastObject];
NSString*?filePath?=[NSStringstringWithFormat:@"%@/%@",?directoryPath,fileName];
returnfilePath;
59.在導(dǎo)航條上添加UI控件
self.navigationItem.titleView=
segment;
60.視圖留白
self.automaticallyAdjustsScrollViewInsets=NO;
61.iOS漢字轉(zhuǎn)為拼音
//城市列表通訊錄右邊索引字母或者拼音如何的到
[objc]view plaincopy
NSMutableString*?hanzi?=[[NSMutableStringalloc]initWithString:@"中華人民共和國(guó)?重慶?長(zhǎng)城?單家莊"];
CFMutableStringRef?hanziRef?=(__bridge?CFMutableStringRef)hanzi;
//CFStringTransform?字符串轉(zhuǎn)化
//kCFStringTransformMandarinLatin?漢字轉(zhuǎn)拼音
//kCFStringTransformStripDiacritics?拼音去音標(biāo)
CFStringTransform(hanziRef,0,?kCFStringTransformMandarinLatin,NO);
NSLog(@"---%@",hanziRef);
CFStringTransform(hanziRef,0,?kCFStringTransformStripDiacritics,NO);
NSLog(@"111---%@",hanziRef);
62.設(shè)備寬高宏定義
#define? DEVICE_WIDTH? [UIScreen mainScreen].bounds.size.width
#define? DEVICE_HEIGHT? [UIScreen mainScreen].bounds.size.height
63:
給button 按鈕設(shè)置背景圖片時(shí) 設(shè)置背景圖片大小 防止圖片變形
[objc]view plaincopy
UIImage*btnImg?=[UIImageimageNamed:[NSStringstringWithFormat:@"button_table_%d",i]];
UIImage*?bbImg?=[btnImgstretchableImageWithLeftCapWidth:100topCapHeight:100];
[btnsetBackgroundImage:bbImgforState:UIControlStateNormal];
64:
異常崩潰處理
在AppDelegate .m 文件中
[objc]view plaincopy
-?(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions?{
//輸出模擬器類型
NSLog(@"%@",[[UIDevicecurrentDevice]model]);
//綁定撲捉異常的函數(shù)?當(dāng)程序崩潰時(shí)?會(huì)先調(diào)用這個(gè)函數(shù)
NSSetUncaughtExceptionHandler(&getException);
returnYES;
}
voidgetException(NSException*exception){
//遇到特殊情況時(shí)?需要把異常的具體信息獲取并儲(chǔ)存
NSLog(@"名字----%@",exception.name);
NSLog(@"原因----%@",exception.reason);
NSLog(@"用戶信息----%@",exception.userInfo);
NSLog(@"棧內(nèi)存地址----%@",exception.callStackReturnAddresses);
NSLog(@"棧描述----%@",exception.callStackSymbols);
NSString*string?=?[NSStringstringWithFormat:@"名字%@,原因%@,信息%@,棧內(nèi)存地址%@,棧描述%@",exception.name,exception.reason,exception.userInfo,exception.callStackReturnAddresses,exception.callStackSymbols];
NSLog(@"%@",string);
NSDate*date?=?[NSDatedate];
//當(dāng)前的系統(tǒng)版本號(hào)
NSString*?version?=[[UIDevicecurrentDevice]systemVersion];
//當(dāng)前設(shè)備型號(hào)
[[UIDevicecurrentDevice]model];
//儲(chǔ)存崩潰信息
NSString*?path?=[NSHomeDirectory()stringByAppendingPathComponent:@"Library/exception.txt"];
[stringwriteToFile:pathatomically:YESencoding:NSUTF8StringEncodingerror:nil];
//當(dāng)程序再次啟動(dòng)時(shí)?把崩潰信息發(fā)送給服務(wù)器
}
65:去除掉首尾的空白字符和換行字符
[objc]view plaincopy
NSString*?headerData?=?[headerDatastringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]];//去除掉首尾的空白字符和換行字符
headerData?=?[headerDatastringByReplacingOccurrencesOfString:@"/r"withString:@""];
headerData?=?[headerDatastringByReplacingOccurrencesOfString:@"/n"withString:@""];
66:為視圖view自定義矩形大小
[objc]view plaincopy
self.edgesForExtendedLayout=?UIRectEdgeNone;
CGRect?viewBounds?=self.view.bounds;
floatnavBarHeight?=self.navigationController.navigationBar.frame.size.height+20;
viewBounds.size.height=?([[UIScreenmainScreen]bounds].size.height)?-?navBarHeight;
self.view.bounds=?viewBounds;