ios 開發小知識點

1.不可變數組轉變為可變數組聲明實例變量的數組? 必須記得實現

對于遍歷數組找到對象后 如果還需要查找 記得先結束 再查找(return/break)

NSArray * arr = @[@"人在囧途",@"煎餅俠",@"西游記",];

NSMutableArray *? arr = [NSMutableArrayarrayWithArray:arr];

在數組中取數據的時候? 需要通過后綴 將數組中的對象轉化為數字類

p11.age=

[newArr[1]intValue];

2.獲取字符串長度NSString * str = nameLabel .text;

CGSizesize=

[strsizeWithAttributes:@{NSFontAttributeName: [UIFontsystemFontOfSize:17]}];

此時即可得到size

.width(字符串的寬? 即 字符串長度)

3.將單獨的某個視圖上的視圖控制器的導航條隱藏

[objc]view plaincopy

-(void)viewDidAppear:(BOOL)animated{

[superviewDidAppear:animated?==NO];

[self.navigationControllersetNavigationBarHidden:YES];

}

4. 邊帽法 (拉伸圖片) 將某一像素點兒不斷地復制? 其他像素點不變 拉伸之后不會是圖片變形

[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. 監聽系統發送的通知

[objc]view plaincopy

//??監聽鍵盤frame發生變化的通知??并可以通過鍵盤的屬性獲得對象

[[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}}";

//一旦鍵盤發生改變的時候??_inputView??和??_tableView?的坐標都要發生改變

//通過字典?獲取對象

NSDictionary*?dic?=?noti.userInfo;

//獲取動畫時長

floattime?=?[[dicobjectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];

//獲取動畫速率

intcurve?=?[[dicobjectForKey:UIKeyboardAnimationCurveUserInfoKey]intValue];

//獲取鍵盤坐標

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.視圖層級切換

關鍵點:

[self .window exchangeSubviewAtIndex:0 withSubviewAtIndex:1];

1.如果父視圖不可交互? 那么放在其上邊的子視圖也不可交互

2. 如果父視圖可以交互? 那么放在上邊的子視圖的可交互性由自己決定

關鍵詞 :userInteractionEnabledimage .userInteractionEnabled=YES;

8.二進制數據轉變類型

字符串轉變為二進制數據

NSString * str = @"girls";

NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];

二進制數據轉變為字符串

NSString * str2 =[[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];

將圖片轉變為二進制數據

1.需要獲得圖片路徑

NSString * imageViewPath =[[NSBundle mainBundle]pathForResource:@"18" ofType:@"jpg"];

NSData * data = [[NSData alloc]initWithContentsOfFile:imageViewPath];

2.直接將添加在工程中的圖片轉化為二進制數據類型

UIImage*

image = [UIImageimageNamed:@"20.jpg"];

NSData*

data =UIImageJPEGRepresentation(image,1);

將轉變為二進制數據的圖片轉變回圖片

方法1 ? 可以直接調用 從路徑中取出圖片

UIImage * image = [UIImage imageWithContentsOfFile:dataPath];

方法2 : 先將路徑中的二進制數據取出? 然后 通過ImageWithData 屬性轉變為圖片類型

NSData * data = [NSData dataWithContentsOfFile:[self getFilePath:@"data.plist"]];

UIImage * image =[UIImage imageWithData:data];

9.如何刪除一個視圖上的所有子視圖? 所有代碼:

獲取視圖上存放的所有子視圖? 遍歷數組 找到所有對象 找到 views

[objc]view plaincopy

for(UIView*?v?inself.view.subviews)?{

[vremoveFromSuperview];

}

10.將某個視圖放在最前邊

[self .view bringSubviewToFront:_tableView];

11.頁面跳轉(需要找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.頁面翻轉

[objc]view plaincopy

[UIViewbeginAnimations:nilcontext:nil];

[UIViewsetAnimationDuration:1];

[UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUpforView:windowcache:YES];

[UIViewcommitAnimations];

2. 模態彈出? (present? 展示 ??? dismiss? 消失 )

3. 導航控制器? (push? 壓棧 ? pop? 出棧 )

//通過導航控制器控制視圖切換的時候

1. 返回上一界面:

[self.navigationControllerpopViewControllerAnimated:YES];

2. 返回根視圖控制器:

[self.navigationControllerpopToRootViewControllerAnimated:YES];

3.返回指定視圖:

//首先獲取目前所有的視圖控制器對象

NSArray*

arr? =self.navigationController.viewControllers;

//從數組中找到需要返回的根視圖

FirestViewController*

first = arr[0];

//返回指定視圖:

[self.navigationControllerpopToViewController:firstanimated:YES];

12.將數據庫文件拷貝到沙盒中

[objc]view plaincopy

//首先需要獲取數據庫文件的路徑??還有文件夾路徑

NSString*?sourePath?=?[[NSBundlemainBundle]pathForResource:@"database"ofType:@"sqlite"];

if(![[NSFileManagerdefaultManager]fileExistsAtPath:@"文件路徑"])?{

NSError*?error?=nil;

if(?[[NSFileManagerdefaultManager]copyItemAtPath:sourePathtoPath:@"文件路徑"error:&error])?{

NSLog(@"copy成功");

}

}

13:直接進入網頁

[objc]view plaincopy

//網頁加載?:

//?創建url???NSURL:?NSObject????用來表示資源在互聯網的位置

NSURL??*?url?=??[NSURLURLWithString:@"http://www.baidu.com"];

//創建一個請求

NSURLRequest*request?=?[NSURLRequestrequestWithURL:url];

//加載請求

[webViewloadRequest:request];

[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"http//www.baidu.com"]];

14:將結構體轉換成字符串再輸出

NSLog(@"-------%@",NSStringFromCGRect(rect));

15:角度轉弧度

可以定義為宏#define

ANGLE_2_HUDU(X) (X)*M_PI/180.0

計算圓形軌跡上控件的中心點坐標時

中心點 ?圓的半徑 ? ?角度轉弧度 ? ? ? 角度值

floatx

= 160 + 100 *cos(ANGLE_2_HUDU(btn.angle));

floaty

= 240 + 100 *sin(ANGLE_2_HUDU(btn

.angle));

//x = 中心點x + 半徑 * cos@

//y = 中心點y + 半徑 *sin@

16:交叉導入

//為了防止交叉導入

@class 文件

//只是告訴了編譯器有這個類? 但是該類的.h文件中有什么東西 編譯器是不知道的 ? 當真正需要使用這個類的時候 還必須在.m 文件中導入#import

"TwoViewController.h”這個頭文件

17: center + bounds = frame ;

//center(設置中心點)

+ bounds(設置寬.高) = frame

image .center = CGPointMake(160, 120);

//bounds (x,y ,width ,height ), 給bounds設置x和y是沒有作用的

image .bounds = CGRectMake(0, 0, 160, 120);

18:查詢父視圖

NSLog(@"==%@",image.superview);

查看view的子視圖

NSLog(@"==%@",self .window .subviews);

19.重新添加xib文件

如果創建的xib 文件的名字不同? 需要在入口方法中調用一下方法

ViewController * vc = [[ViewController alloc]initWithNibName:@"Empty" bundle:nil];

20.屏幕獲取觸摸對象

[objc]view plaincopy

-(void)touchesMoved:(NSSet*)toucheswithEvent:(UIEvent*)event?{

//獲取觸摸對象

UITouch*?touch?=[touchesanyObject];

//獲取觸摸對象?在某一視圖上的一個點

CGPoint?point?=?[touchlocationInView:self.view];

//把結構體轉換為字符串輸出

NSLog(@"---%@",NSStringFromCGPoint(point));

//CGRectContainsPoint??作用??:?判斷CGRect???數據是否包含一個點?point?如果包含這個點?函數值就是1

//類似屬性?CGRectIntersectsRect(CGRect?rect1,?CGRect?rect2)?判斷兩個坐標是否有交集

//NO1.?觸摸對象坐標??NO2.結構體

if(CGRectContainsPoint(self.view.frame,?point))?{

self.view.center=?point;

}

}

21:判斷對象之間聯系常用的屬性

1.判斷某個對象坐標時候包含某個點

CGRectContainsPoint(self.frame.frame, point)

2. 判斷兩個坐標是否有交集

CGRectIntersectsRect(rect1, ?rect2)

3.判斷兩個對象時候相等的時候

isEqualToString:

4. 判斷字符串類型數據長度的時候 需要調用length

22.獲取系統當前時間

[objc]view plaincopy

NSDate*?date?=?[NSDatedate];

//時間格式?年yyyy?月?MM?日dd?小時?HH?分鐘?mm?秒?ss

NSDateFormatter*?formatter??=?[[NSDateFormatteralloc]init];

[formattersetDateFormat:@"yy-MM-dd?HH-mm-ss"];

NSString*str?=?[formatterstringFromDate:date];

NSLog(@"-=-=-=-=-=-=-===%@",str);

23. 分割(返回值類型 - 數組)? . 拼接字符串

//分割:

NSArray * arr =[str componentsSeparatedByString:@" "];

//字符串之間用什么隔開 分割時? 在@“” 中就調用什么 (eg: |? 空格 等);

//拼接:

[NSString stringWithString:@""]

[NSString stringWithFormat:@""]

去掉字符串中間的空格

return [self stringByReplacingOccurrencesOfString:@" " withString:@""];

去掉字符串的換行符

str =[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

24 .定時器 .延遲加載

//定時器開啟的時候 為防止點擊按鈕時開啟多個定時器造成混亂? 所以在開啟定時器的時候可以先判斷時候有開啟定時器

方法1:

[objc]view plaincopy

staticBOOLisOk;

if(isOk?==NO)?{

NSTimer*?timer?=??[NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(onTimer)userInfo:nilrepeats:YES];

//開啟定時器后?如果想要定時器立即開啟?可以調用

[timerfire];

isOk?=YES;

}

方法2 :

[objc]view plaincopy

if(_timer)?{

return;

}

_timer?=??[NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(onTimer)userInfo:nilrepeats:YES];

//關閉定時器時??記得立即將其指為空

[_timerinvalidate];

_timer?=nil;

延時加載

[objc]view plaincopy

//定時器綁定方法的時候??只能講自身傳過來

_timer?=?[NSTimerscheduledTimerWithTimeInterval:0.05target:selfselector:@selector(onTimer:)userInfo:?buttonrepeats:YES];

-(void)onTimer:?(NSTimer*)aTimer{

//通過userInfo?獲取點擊的按鈕

UIButton*?clickBtn?=?aTimer.userInfo;

}

//延遲加載?要點??需要調用performSelector

[selfperformSelector:@selector()withObject:nilafterDelay:5];

25 .文本框結束編輯的時候? 讓鍵盤下去

[objc]view plaincopy

-(void)touchesBegan:(NSSet*)toucheswithEvent:(UIEvent*)event{

[self.windowendEditing:YES];

}

26:向相冊中保存圖片

[objc]view plaincopy

UIImageWriteToSavedPhotosAlbum([UIImageimageNamed:@"20.jpg"],self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);

//必要實現的協議方法,?不然會崩潰

-?(void)image:(UIImage*)imagedidFinishSavingWithError:(NSError*)errorcontextInfo:(voidvoid*)contextInfo?{

}

27.輸出當前所在的方法名:

NSLog(@"-----%s---", __func__);

28.三目運算符

條件 ?(執行操作) : 其它操作

number = i <= 8 ?(i + 1) : 0? 解釋 : 當i 小于等于8 時? 執行 i+1 的操作? 否則? 執行冒號后面的操作? 即 i = 0;

29.在數組中隨機取出數據

1) 首先先在數組中隨機出一個索引

int? random = arc4random()%numberArray .count;

2) 將取出的數據轉化為想要的類型

int number = [numberArray [random] intvalue];

3) 將取出的數據在數組中刪除 ? 以防止隨機重復

[numberArray removeObjectAtIndex : random];

30.視圖修剪 .透明度? 隱藏視圖 移除視圖 :

clip? 修剪? bounds 邊界

1.是否對視圖修剪

bigView .clipsToBounds=YES;

2.設置圓角半徑

bigView .layer.cornerRadius=

90;

bigView.layer.masksToBounds=YES;

3.透明度:

_view .alpha = 0;

4.移除視圖 :

[_view removeFromSuperview];

31: 字符串拼接輸出控件屬性值

NSLog(@"

= %@",NSStringFromCGRect(nav.navigationBar.frame));

32:第一響應:

1.打開程序時? 文本框處于編輯狀態 即? 第一響應

成為第一響應 [_textfieldbecomeFirstResponder];

失去第一響應[_textfield resignFirstResponder];

2.在tocubegin協議方法中調用

[self.view endEditing: YES]

33 .導航控制器相關控件內容

1.設置導航條的背景顏色

錯誤做法:nav

.navigationBar.backgroundColor=

[UIColorgrayColor];

正確做法:nav

.navigationBar.barTintColor=

[UIColorgrayColor];

2.設置導航條標題self.title=@"導航條";

3. 設置左右欄按鈕項 (記得按鈕綁定方法的實現)

[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.隱藏導航條 :

//注意: 隱藏導航條的時候 不能混著用 怎么讓導航條隱藏的 就怎么讓導航條出現 :

方法1:

[self.navigationControllersetNavigationBarHidden:YES];

[self.navigationControllersetNavigationBarHidden:YESanimated:YES];

方法2:self.navigationController.navigationBarHidden=YES;

self.navigationController.navigationBarHidden=NO;

補充 :? 在視圖將要顯示的時候? 隱藏導航條 :

[objc]view plaincopy

-(void)viewWillAppear:(BOOL)animated?{

[superviewWillAppear:animated];

[self.navigationControllersetNavigationBarHidden:YES];

}

5.設置導航條按鈕項時候添加圖片? (圖片渲染)

[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;//設置內容樣式,通過保持長寬比縮放內容適應視圖的大小,任何剩余的區域的視圖的界限是透明的

///按鈕設置背景圖片時?設置背景圖片大小?防止圖片變形

UIImage*?btnImg?=?[UIImageimageNamed:@"button_table"];

UIImage*?bbImg?=?[btnImgstretchableImageWithLeftCapWidth:100topCapHeight:100];

6. 隱藏導航條自定義的返回按鈕 :

self.navigationItem.hidesBackButton=YES;

7.導航條上添加控件

self.navigationItem.titleView = 控件對象;

34.彈框

iOS8以后推薦使用UIAlertController

樣式1: UIAlertView

[objc]view plaincopy

UIAlertView*alertView?=[[UIAlertViewalloc]initWithTitle:@"提示"message:@"新建聯系人"delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"確定",nilnil];

//彈框樣式?:(帶輸入框)

alertView.alertViewStyle=UIAlertViewStyleLoginAndPasswordInput;

UITextField*field1=[alertViewtextFieldAtIndex:0];

UITextField*field2=[alertViewtextFieldAtIndex:1];

field1.placeholder=@"請輸入姓名";

field2.placeholder=@"請輸入電話";

field2.secureTextEntry=NO;

[alertViewshow];

//實現 alertView? 首先在.h文件中 實現協議

實現協議方法:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

//通過buttonIndex 的索引值 判斷點擊的是哪個按鈕? 0 ,1

樣式2:ActionSheet

//ActionSheet

不可以在viewDidLoad 方法中創建? 這是因為 ActionSheet 是在self .view 上展示的

此時我們的viewDidLoad 方法還沒有走完 ? 我們的self.view 就不能展示出來 self.view 還沒有展示

那么我們放在self.view上的actionsheet 也就無法展示

UIActionSheet*

actionSheet = [[UIActionSheetalloc]initWithTitle:@"提示"delegate:selfcancelButtonTitle:@"取消"destructiveButtonTitle:@"確定"otherButtonTitles:nil,nil];

[actionSheetshowInView:self.view];

7.設置cell的背景顏色

[objc]view plaincopy

-(void)tableView:(UITableView*)tableViewwillDisplayCell:(UITableViewCell*)cellforRowAtIndexPath:(NSIndexPath*)indexPath?{

[cellsetBackgroundColor:[UIColorblackColor]];

}

35.

九宮格

[objc]view plaincopy

//方法1:?嵌套for?循環

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?.單個for循環

//?三行三列

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.服務器

- 去掉out.println --句中的ln換行符

str =[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

38.如果URL中路徑的字符串拼接的時候

有中文 需要編碼

NSString*encodingString

= [pathstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

39.獲取沙盒文件中某個文件夾下的所有內容

contentsOfDirectoryAtPath

[objc]view plaincopy

NSString*filePath?=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];

//返回值類型是數組

NSArray*arr?=??[[NSFileManagerdefaultManager]contentsOfDirectoryAtPath:filePatherror:nil];

NSLog(@"arr===%@",arr);

40 .獲取沙盒文件中某個文件的屬性

[objc]view plaincopy

NSString*filePath?=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/str.plist"];

//返回值類型是字典??所以我們可以通過字典內的鍵值??取出我們想要的數據

NSDictionary*dic?=?[[NSFileManagerdefaultManager]attributesOfItemAtPath:filePatherror:nil];

unsignedlonglongsize=?[dicfileSize];

NSLog(@"----%llu",size);

NSLog(@"dic====%@",dic);

41:輸出對象的時候設置輸出字符串格式調用的方法

[objc]view plaincopy

//輸出對象的時候?會調用該對象的description?方法

-(NSString*)description{

return[NSStringstringWithFormat:@"IP-----%p???name----%@???age-----%d",self,self.name,self.age];

}

42:沙盒文件中路徑查找的便捷方式

1.獲取根目錄文件路徑

NSLog(@"-----%@",NSHomeDirectory());

2.獲取臨時文件路徑方法類似于獲取根目錄文件路徑

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:對象序列化

歸檔步驟 :

1. 創建可變的data (相當于一個空的袋子 )NSMutableData*

data= [[NSMutableDataalloc]initWithCapacity:0];

2.歸檔? 關鍵詞 : archiver

NSKeyedArchiver*

archiver = [[NSKeyedArchiveralloc]initForWritingWithMutableData:data];

3.編碼 : (就是將對象類轉變為二進制數據的過程)

[archiver encodeObject:_arr];

//如果有多個對象的時候 通過 設置 key值來區分

[archiverencodeObject:_arrforKey:@"arr"];

[archiverencodeObject:_viewforKey:@"view"];

4.結束編碼的時候? 必須調用 接收方法 (完成編碼)

[archiverfinishEncoding];

5.可以將轉變為二進制數據類型的 對象類寫入沙盒中

[datawriteToFile:

[selfgetFilePath]atomically:YES];

反序列化 (將二進制數據類型 轉換為對象類)

1. 在沙盒中取出data數據

NSData*

data = [[NSDataalloc]initWithContentsOfFile:[selfgetFilePath]];

2.將取出的數據交給反序列化來讀

NSKeyedUnarchiver*

unarchiver = [[NSKeyedUnarchiveralloc]initForReadingWithData:data];

3.解碼

NSArray * arr =? [unarchiver decodeObject];

//如果有多個對象 (如上)

NSArray*

arr = [unarchiverdecodeObjectForKey:@"arr"];

4.結束解碼 :

[unarchiverfinishDecoding];

補充 :? 為了調取路徑方法方便? 可以將獲取路徑封裝成方法 便于調用

[objc]view plaincopy

-(NSString*)getFilePath{

return[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/arr.plist"];

}

2.自定義對象轉碼的時候

1. 需要在.h文件中必須實現的協議

2.在.m 文件中必須實現的兩個方法

//將people類中的屬性進行編碼

//aCoder 編碼器

//當用序列化器編碼對象的時候 , 該方法就會被調用

[objc]view plaincopy

-(void)encodeWithCoder:(NSCoder*)aCoder{

NSLog(@"3333333333");

[aCoderencodeObject:_nameforKey:@"name"];

[aCoderencodeInt:_ageforKey:@"age"];

}

//解碼

//aDecoder 解碼器

//反序列化時 將NSData 解碼成對象類型調用的方法

[objc]view plaincopy

-(id)initWithCoder:(NSCoder*)aDecoder?{

//任意類型??初始化[super?init]?方法

self=?[superinit];

if(self)?{

//需要self.屬性??接收

self.name=?[aDecoderdecodeObjectForKey:@"name"];

self.age=?[aDecoderdecodeIntForKey:@"age"];

}

returnself;

}

補充 :? 如果再創建一個類? 繼承與自定義people類時

實現第二個協議方法時 (返回值為id 的協議方法? ) 需要先繼承父類方法 即:

[objc]view plaincopy

-(id)initWithCoder:(NSCoder*)aDecoder?{

self=?[superinitWithCoder:aDecoder];

if(self)?{

[aDecoderdecodeObjectForKey:@"huzi"];

}

returnself;

}

快速轉碼? :

1.直接將對象放在沙盒中

[NSKeyedArchiverarchiveRootObject:_arrtoFile:[selfgetFilePath]];

2. 在反序列化中直接取出對象

NSArray*

arr = [NSKeyedUnarchiverunarchiveObjectWithFile:[selfgetFilePath]];

44:NSUserDefaults儲存數據

(儲存輕量級的數據(賬號 密碼? 是否登錄))

//1.NSUserDefaults 可以存儲的數據類型 : NSString? 字典? 數組? NSNumber BOOL NSData(二進制數據) NSDate(時間) int(integer)? Double ? float, URL(網址)

//2.強制數據及時存儲到沙盒

//userDefaults向沙盒中儲存數據是按照一定的時間戳定時儲存數據如果數據還沒來得及存儲而此時程序出現問題那么數據就會丟失所以我們可以同步一下強制數據及時存儲到沙盒

//synchronize同步保證數據及時的儲存到沙盒中

[userDefaults synchronize];

45: NSUserDefaults存取文件

[objc]view plaincopy

//存數據:

[[NSUserDefaultsstandardUserDefaults]setObject:_nameField.textforKey:@"name"];

[[NSUserDefaultsstandardUserDefaults]setObject:_pswField.textforKey:@"psw"];

//同步數據

[[NSUserDefaultsstandardUserDefaults]synchronize];

//取數據:

NSString*?nameString?=??[[NSUserDefaultsstandardUserDefaults]objectForKey:@"name"];

NSString*?pswString??=[[NSUserDefaultsstandardUserDefaults]objectForKey:@"psw"];

46:判斷某路徑下是否存在文件

是不是文件夾??? 關鍵詞 :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(@"是個文件夾");

}else{

NSLog(@"不是文件夾");

}

}else{

NSLog(@"不存在文件");

}

47 .網絡請求中網絡超時設置request .timeoutInterval = 10;

48.單元格關鍵控件摘要

1.分割線顏色樣式:

tableVew .separatorColor=[UIColorredColor];

tableVew .separatorStyle=UITableViewCellSeparatorStyleNone;

2.單元格背景View

可以設置圖片 下拉的時候顯示

tableVew .backgroundView=imageView;

3.單元格表頭背景View可以設置圖片因為需要設置坐標可以通過封裝方法然后在ViewDidLoad

方法中調用

tableVew.tableHeaderView=imageView;

4.視圖修剪

cell.imageView.layer.cornerRadius=50;

cell.imageView.layer.masksToBounds=YES;

5.cell小掛件

cell .accessoryType=UITableViewCellAccessoryDetailButton;

6.點擊單元格時候的樣式:

cell .selectionStyle=UITableViewCellSelectionStyleNone;

7.如果想把單元格的白色背景去掉的話

需要將tableView 和cell 上的背景顏色都設置為clearColor

8.點擊單元格上的按鈕時候在按鈕綁定的方法中找到點擊的是哪一行上的按鈕需要通過按鈕找到cell? 再通過cell 找到IndexPath

eg:UITableViewCell*

cell =(UITableViewCell*)btn.superview.superview;NSIndexPath*

indexPath =[_tableViewindexPathForCell:cell];

9.區頭區尾相關內容

//也需要重用區頭和區尾的設置中 相關的控件設置和添加需要放在cell.contentView

e.g:

1.cell.contentView.backgroundColor=

[UIColorgrayColor];

2.[cell.contentViewaddSubview:img];

10.單元格索引:

將索引標示放在數組中

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",@"#",];索引調用的方法:

[objc]view plaincopy

-(NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView?{

return_arr;

}

49. btn按鈕的失去響應

btn .enabled = NO;

//默認值 YES

btn.enabled = YES;

50.在為URL添加字符串時

包含特殊字符或中文的 需要編碼轉換

string =[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

51.圖片轉化為二進制數據

//兩種方法都可以 但是 PNG的返回的圖片量與原圖大小差不多 而jpg 的會壓縮參數NSData * data = UIImagePNGRepresentation(self.imageView.image);

NSData * data = UIImageJPEGRepresentation(self.imageView.image, 0.1);

52.斷點下載個別屬性摘要

1. 獲取已經下載文件的大小 文件較大的時候 可以用long long 創建實例變量

_receiveSize =[dic fileSize];

2.通過Range

頭 —> 可以指定每次從網上下載數據包的大小

[request addValue:[NSString stringWithFormat:@"bytes=%lld-",_receiveSize] forHTTPHeaderField:@"Range"];

3.期望從服務器中返回的剩余的數據expectedContentLength

long long lastSize = response.expectedContentLength;

4.受到響應的時候

需要創建對象 并給對象一個寫文件的路徑

_fileHandle =? [NSFileHandle fileHandleForWritingAtPath:[self getPath]];

//找到已經下載文件的結尾數據[_fileHandle seekToEndOfFile];

//寫入數據

[_fileHandle writeData:data];

//開始在接受數據的協議方法中不斷的追加數據

_receiveSize +=[data length];

5.下載進度賦值到進度條

//當前下載比例=接收數據/總數據

float progress =(float) _receiveSize /_totalSize;

self.weak.progress = progress;

self .persentLabel.text = [NSString stringWithFormat:@"%.2f%%",progress*100];

6.暫停數據綁定的方法中

暫停請求數據 同時將請求數據指為空 (類似于定時器)

[_connection cancel];

_connection = nil;

53.OC中對用戶名和密碼編碼和加密常用的方法base64 MD5

//在需要加密內容的后面添加后綴

[_nameField.textbase64EncodedString]編碼

[_nameField.textbase64DecodedString]解碼

[_pswField.textMD5]加密

54.在web請求體重? 截取某個字段

@"https://api.weibo.com/oauth2/authorize?client_id=1950801855&response_type=code&redirect_uri=http://www.baidu.com"該請求體中的code

NSRangerange

=[request.URL.absoluteStringrangeOfString:@"code="];

NSString*

code =[[request.URL.absoluteStringcomponentsSeparatedByString:@"="]lastObject];

都是單純地字符串操作

55.判斷授權token

和 過期時間的兩種方式 :

[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"];

//過期時間

NSDate*?date?=?[[NSUserDefaultsstandardUserDefaults]objectForKey:@"date"];

if(token?==nil||?[tokenisEqualToString:@""])?{

returnNO;

}

//當前時間

NSDate*?currentDate?=[NSDatedate];

//當前時間和過期時間?對比

if([[currentDatelaterDate:date]isEqualToDate:currentDate])?{

returnNO;

}

returnYES;

56.如果需要設置多個tag值時

//一般設置tag值只需要設置為數字進行區分的話 就可以 但是如果接口較多 需要區分的話 單獨的設置為數字 時間久的話 不好辨認 所以我們可以模仿系統? 來寫出一個枚舉來

// NSInteger指的是枚舉中值的類型RequestType總的請求類型

typedefNS_ENUM(NSInteger, RequestType) {

GetTokenRequestTag = 0,

GetStatusListRequestTag

//需要再往下寫的時候? 不需要設置數字就可以 因為系統會自動遞增

};

調用時: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.查找某個具體文件(eg:圖片)路徑的方法

[objc]view plaincopy

NSString*?directoryPath?=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/ImageCache"];

//保證沙盒中的Documents?中一定有一個ImageCache?文件夾

if(![[NSFileManagerdefaultManager]fileExistsAtPath:directoryPath])?{

[[NSFileManagerdefaultManager]createDirectoryAtPath:directoryPathwithIntermediateDirectories:YESattributes:nilerror:nil];

}

//把圖片的地址字符串分割?最后一個/?之后的那段就是圖片的名字

NSString*?fileName?=[[@"URLString"componentsSeparatedByString:@"/"]lastObject];

NSString*?filePath?=[NSStringstringWithFormat:@"%@/%@",?directoryPath,fileName];

returnfilePath;

59.在導航條上添加UI控件

self.navigationItem.titleView=

segment;

60.視圖留白

self.automaticallyAdjustsScrollViewInsets=NO;

61.iOS漢字轉為拼音

//城市列表通訊錄右邊索引字母或者拼音如何的到

[objc]view plaincopy

NSMutableString*?hanzi?=[[NSMutableStringalloc]initWithString:@"中華人民共和國?重慶?長城?單家莊"];

CFMutableStringRef?hanziRef?=(__bridge?CFMutableStringRef)hanzi;

//CFStringTransform?字符串轉化

//kCFStringTransformMandarinLatin?漢字轉拼音

//kCFStringTransformStripDiacritics?拼音去音標

CFStringTransform(hanziRef,0,?kCFStringTransformMandarinLatin,NO);

NSLog(@"---%@",hanziRef);

CFStringTransform(hanziRef,0,?kCFStringTransformStripDiacritics,NO);

NSLog(@"111---%@",hanziRef);

62.設備寬高宏定義

#define? DEVICE_WIDTH? [UIScreen mainScreen].bounds.size.width

#define? DEVICE_HEIGHT? [UIScreen mainScreen].bounds.size.height

63:

給button 按鈕設置背景圖片時 設置背景圖片大小 防止圖片變形

[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]);

//綁定撲捉異常的函數?當程序崩潰時?會先調用這個函數

NSSetUncaughtExceptionHandler(&getException);

returnYES;

}

voidgetException(NSException*exception){

//遇到特殊情況時?需要把異常的具體信息獲取并儲存

NSLog(@"名字----%@",exception.name);

NSLog(@"原因----%@",exception.reason);

NSLog(@"用戶信息----%@",exception.userInfo);

NSLog(@"棧內存地址----%@",exception.callStackReturnAddresses);

NSLog(@"棧描述----%@",exception.callStackSymbols);

NSString*string?=?[NSStringstringWithFormat:@"名字%@,原因%@,信息%@,棧內存地址%@,棧描述%@",exception.name,exception.reason,exception.userInfo,exception.callStackReturnAddresses,exception.callStackSymbols];

NSLog(@"%@",string);

NSDate*date?=?[NSDatedate];

//當前的系統版本號

NSString*?version?=[[UIDevicecurrentDevice]systemVersion];

//當前設備型號

[[UIDevicecurrentDevice]model];

//儲存崩潰信息

NSString*?path?=[NSHomeDirectory()stringByAppendingPathComponent:@"Library/exception.txt"];

[stringwriteToFile:pathatomically:YESencoding:NSUTF8StringEncodingerror:nil];

//當程序再次啟動時?把崩潰信息發送給服務器

}

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;

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,797評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,179評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,628評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,642評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,444評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,948評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,040評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,185評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,717評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,602評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,794評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,316評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,045評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,418評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,671評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,414評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,750評論 2 370

推薦閱讀更多精彩內容