一个iOS开发者必须掌握的66个知识点,你掌握了多少?

1. 不可变数组  转变为可变数组 
声明实例变量的数组  必须记得实现

对于遍历数组找到对象后 如果还需要查找 记得先结束 再查找(return/break)

NSArray * arr = @[@"人在囧途",@"煎饼侠",@"西游记",];

NSMutableArray *  arr = [NSMutableArray arrayWithArray:arr];

在数组中取数据的时候  需要通过后缀 将数组中的对象转化为数字类
p11. age   = [newArr[1] intValue ];



2.获取字符串长度 
NSString * str = nameLabel .text;
CGSize
  size   = [str   sizeWithAttributes :@{ NSFontAttributeName : [UIFont systemFontOfSize:17]}];
此时即可得到
  size .width   (字符串的宽  即 字符串长度)



3.将单独的某个视图上的视图控制器的导航条隐藏 
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated == NO];
    [self .navigationController setNavigationBarHidden:YES];
}



4. 边帽法 (拉伸图片) 将某一像素点儿不断地复制  其他像素点不变 拉伸之后不会是图片变形
//第一种
    [[UIImageView alloc] init].image = [[UIImage imageNamed:@"bubble.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20];
    //第二种
    UIImage * image =[UIImage imageNamed:@"7.jpg"];
    [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, image.size.width, 0, 0)];
    [[UIImageView alloc] init].image = image;



5. 监听系统发送的通知 
//  监听键盘frame发生变化的通知  并可以通过键盘的属性获得对象
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(KeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object: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;
        
        //获取动画时长
        float time = [[dic objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        
        //获取动画速率
        int curve = [[dic objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
        
        //获取键盘坐标
        CGRect rect = [[dic objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    }



6.通过字符串绘制矩形  MAXFLOAT 无限
NSString * str = _chatArr[indexPath .row];
CGRect rect = [str  boundingRectWithSize:CGSizeMake(200, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil];


7.视图层级切换 
关键点:
 [self .window exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
1.   如果父视图不可交互  那么放在其上边的子视图也不可交互
2. 如果父视图可以交互  那么放在上边的子视图的可交互性由自己决定
关键词 :
  userInteractionEnabled
image . 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 = [UIImage imageNamed:@"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
for (UIView * v in self.view.subviews) {
    [v removeFromSuperview];
}



10.将某个视图放在最前边
 [self .view bringSubviewToFront:_tableView];



11.页面跳转(需要找window)
//
window
 方法 1:

UIWindow * window =[[[UIApplication sharedApplication]delegate]window];
window .rootViewController = aViewController;

 方法 2:

UIApplication * app = [UIApplication sharedApplication];
AppDelegate * delegate = app .delegate;
UIWindow * window = delegate .window ;
window .rootViewController = aViewController;



1.
  页面翻转
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:window cache:YES];
[UIView commitAnimations];

2. 模态弹出  (present  展示     dismiss  消失 )

3. 导航控制器  (push  压栈   pop  出栈 )

//通过导航控制器控制视图切换的时候

1. 返回上一界面:

 [ self   . navigationController   popViewControllerAnimated : YES ];

2. 返回根视图控制器:

[ self   . navigationController   popToRootViewControllerAnimated : YES ];

3.返回指定视图:

//首先获取目前所有的视图控制器对象

NSArray * arr  =  self .navigationController .viewControllers;

//从数组中找到需要返回的根视图

FirestViewController * first = arr[0];

//返回指定视图:

 [self .navigationController popToViewController:first animated:YES];



12.将数据库文件拷贝到沙盒中 

//首先需要获取数据库文件的路径  还有文件夹路径
    NSString * sourePath = [[NSBundle mainBundle]pathForResource:@"database" ofType:@"sqlite"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:@"文件路径"]) {
        NSError * error = nil;
        if ( [[NSFileManager defaultManager]copyItemAtPath:sourePath toPath:@"文件路径" error:&error]) {
            NSLog(@"copy成功");
        }
    }


13:直接进入网页 

//网页加载 :
// 创建url   NSURL: NSObject    用来表示资源在互联网的位置
NSURL  * url =  [NSURL URLWithString:@"http://www.baidu.com"];
//创建一个请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//加载请求
[webView loadRequest:request];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http//www.baidu.com"]];



14:将结构体转换成字符串再输出

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



15: 角度转弧度 

可以定义为宏 #define ANGLE_2_HUDU(X) (X)*M_PI/180.0    

计算圆形轨迹上控件的中心点坐标时 
             中心点  圆的半径    角度转弧度       角度值  
float   x = 160 + 100 *   cos ( ANGLE_2_HUDU (btn. angle ));

float y = 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.屏幕获取触摸对象 
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    //获取触摸对象
    UITouch * touch =[touches anyObject];
    //获取触摸对象 在某一视图上的一个点
    CGPoint point = [touch locationInView: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.获取系统当前时间 
NSDate * date = [NSDate date];
    //时间格式 年yyyy 月 MM 日dd 小时 HH 分钟 mm 秒 ss
    NSDateFormatter * formatter  = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yy-MM-dd HH-mm-ss"];
    NSString *str = [formatter stringFromDate:date];
    NSLog(@"-=-=-=-=-=-=-===%@",str);



23. 分割(返回值类型 - 数组)  . 拼接字符串 

//分割:

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

//字符串之间用什么隔开 分割时  在@“” 中就调用什么 (eg: |  空格 等);

//拼接:
[NSString stringWithString:@""]

[NSString stringWithFormat:@""]


去掉字符串中间的空格

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

去掉字符串的换行符 

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


24 .定时器 .延迟加载 
//定时器开启的时候 为防止点击按钮时开启多个定时器造成混乱  所以在开启定时器的时候可以先判断时候有开启定时器
方法1:
static BOOL isOk;
    if (isOk == NO) {
        NSTimer * timer =  [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
        //开启定时器后 如果想要定时器立即开启 可以调用
        [timer fire];
        isOk = YES;
    }

方法2 :
if (_timer) {
        return;
    }
    _timer =  [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    //关闭定时器时  记得立即将其指为空
    [_timer invalidate];
    _timer = nil;

延时加载

//定时器绑定方法的时候  只能讲自身传过来
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer:) userInfo: button repeats:YES];
    -(void)onTimer: (NSTimer *)aTimer{
        //通过userInfo 获取点击的按钮
        UIButton * clickBtn = aTimer.userInfo;
    }
    //延迟加载 要点  需要调用performSelector
    [self performSelector:@selector() withObject:nil afterDelay:5];



25 .文本框结束编辑的时候  让键盘下去 
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self .window endEditing:YES]; 
}



26:向相册中保存图片 

UIImageWriteToSavedPhotosAlbum([UIImage imageNamed:@"20.jpg"], self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//必要实现的协议方法, 不然会崩溃
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)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.打开程序时  文本框处于编辑状态 即  第一响应

成为第一响应 [_textfield becomeFirstResponder ];

失去第一响应   [_textfield resignFirstResponder];

2.在tocubegin协议方法中调用

[self.view endEditing: YES]



33 .导航控制器相关控件内容 

1.设置导航条的背景颜色

错误做法:  nav .navigationBar.backgroundColor = [UIColor grayColor];

正确做法:   nav . navigationBar . barTintColor   = [ UIColor   grayColor ];

2.设置导航条标题
self   . title   = @"导航条" ;

3. 设置左右栏按钮项 (记得按钮绑定方法的实现)
UIBarButtonItem * lifeItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self  action:(@selector(baoCunBtnClick:))];
    self .navigationItem .leftBarButtonItem = lifeItem;
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"添加分组" style:UIBarButtonItemStylePlain target:self  action:(@selector(addGrounpBtnClick:))];
    self .navigationItem .rightBarButtonItem = rightItem;

4.隐藏导航条 :

//注意: 隐藏导航条的时候 不能混着用 怎么让导航条隐藏的 就怎么让导航条出现 :

方法1:
[
self   . navigationController   setNavigationBarHidden : YES ];
[
self   . navigationController   setNavigationBarHidden : YES   animated : YES ];

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

补充 :  在视图将要显示的时候  隐藏导航条 :
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self .navigationController setNavigationBarHidden:YES];
}


5.设置导航条按钮项时候添加图片  (图片渲染)

UIImage * image = [[UIImage imageNamed:@"back"]imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem * backBar = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(backClick)];
    self.navigationItem .leftBarButtonItem = backBar;
    self.navigationController.view.contentMode = UIViewContentModeScaleAspectFit;//设置内容样式,通过保持长宽比缩放内容适应视图的大小,任何剩余的区域的视图的界限是透明的
    ///按钮设置背景图片时 设置背景图片大小 防止图片变形
    UIImage * btnImg = [UIImage imageNamed:@"button_table"];
    UIImage * bbImg = [btnImg stretchableImageWithLeftCapWidth:100 topCapHeight:100];

6. 隐藏导航条自定义的返回按钮 :

self.navigationItem.hidesBackButton = YES; 


7.导航条上添加控件    

self.navigationItem.titleView = 控件对象;  



34.弹框

iOS8以后推荐使用UIAlertController

样式1: UIAlertView

UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"提示" message:@"新建联系人" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    //弹框样式 :(带输入框)
    alertView.alertViewStyle =UIAlertViewStyleLoginAndPasswordInput;
    UITextField *field1 =[alertView textFieldAtIndex:0];
    UITextField *field2 =[alertView textFieldAtIndex:1];
    field1.placeholder =@"请输入姓名";
    field2.placeholder =@"请输入电话";
    field2.secureTextEntry=NO;
    [alertView show];

//实现 alertView  首先在.h文件中 实现协议 <UIAlertViewDelegate>

实现协议方法:

-(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 = [[UIActionSheet alloc]initWithTitle:@"提示" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil, nil];

[actionSheet showInView:self .view]; 


7.设置cell的背景颜色 

 -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setBackgroundColor:[UIColor blackColor]];
} 



35. 九宫格 
//方法1: 嵌套for 循环
    for (int a = 0 ; a <2; a ++) {
        for (int b = 0 ; b < 3 ; b++) {
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
            btn .backgroundColor = [UIColor redColor];
            btn .frame = CGRectMake(30 + (320-70)*a, 80 + (60 + 40) * b, 40, 40);
            [self .view addSubview:btn];
        }
    }
    
    //方法2 .单个for循环
    // 三行三列
    for (int a = 0;  a < 9 ; a ++) {
        float jiange = (320 - 40 *3)/4;
        int x = a%3;
        int y = a/3;
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn .backgroundColor = [UIColor redColor];
        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 = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 


39.获取沙盒文件中某个文件夹下的所有内容 contentsOfDirectoryAtPath 
NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //返回值类型是数组
    NSArray *arr =  [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil];
    NSLog(@"arr===%@",arr);


40 .获取沙盒文件中某个文件的属性 
NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/str.plist"];
    //返回值类型是字典  所以我们可以通过字典内的键值  取出我们想要的数据
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    unsigned long long size= [dic fileSize];
    NSLog(@"----%llu",size);
    NSLog(@"dic====%@",dic);



41: 输出对象的时候 设置输出字符串格式 调用的方法 
//输出对象的时候 会调用该对象的description 方法
-(NSString *)description{
    return [NSString stringWithFormat:@"IP-----%p   name----%@   age-----%d",self, self.name, self.age];
}


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

1.获取根目录文件路径 

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

2.获取临时文件路径  方法类似于获取根目录文件 路径

NSString * temp = NSTemporaryDirectory();

3.获取资源包路径

NSString  *appPath =    [[NSBundle mainBundle]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= [[ NSMutableData   alloc ] initWithCapacity :0];

2.归档  关键词 : archiver 

NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];


3.编码 : (就是将对象类转变为二进制数据的过程)

[archiver encodeObject:_arr];

//如果有多个对象的时候 通过 设置 key值来区分

[archiver encodeObject:_arr forKey:@"arr"];

[archiver encodeObject:_view forKey:@"view"];


4.结束编码的时候  必须调用 接收方法 (完成编码)

[archiver finishEncoding];


5.可以将转变为二进制数据类型的 对象类写入沙盒中

[data   writeToFile :  [ self   getFilePath ]   atomically : YES ];


反序列化 (将二进制数据类型 转换为对象类)

1. 在沙盒中取出data数据

NSData   * data = [[ NSData   alloc initWithContentsOfFile :[ self   getFilePath ]];

2.将取出的数据交给反序列化来读

NSKeyedUnarchiver   * unarchiver = [[ NSKeyedUnarchiver   alloc initForReadingWithData :data];

3.解码

NSArray * arr =  [unarchiver decodeObject];

//如果有多个对象 (如上)

NSArray   * arr = [unarchiver   decodeObjectForKey : @"arr" ];

4.结束解码 :

[unarchiver finishDecoding];


补充 :  为了调取路径方法方便  可以将获取路径封装成方法 便于调用

-(NSString *)getFilePath{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/arr.plist"];
}


2. 自定义对象转码的时候  

1. 需要在.h文件中必须实现的协议

2. .m 文件中必须实现的两个方法

//将people类中的属性进行编码

//aCoder 编码器

//当用序列化器编码对象的时候 , 该方法就会被调用

-(void)encodeWithCoder:(NSCoder *)aCoder{
    NSLog(@"3333333333");
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInt:_age forKey:@"age"];
}


//解码

//aDecoder 解码器

//反序列化时 将NSData 解码成对象类型调用的方法

-(id)initWithCoder:(NSCoder *)aDecoder {
    //任意类型  初始化[super init] 方法
    self = [super init];
    if (self) {
        //需要self.属性  接收
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntForKey:@"age"];
    }
    return self;
}


补充 :  如果再创建一个类  继承与自定义people类时 

实现第二个协议方法时 (返回值为id 的协议方法  ) 需要先继承父类方法 即:

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [aDecoder decodeObjectForKey:@"huzi"];
    }
    return self;
}

快速转码  :

1.直接将对象放在沙盒中

[ NSKeyedArchiver   archiveRootObject : _arr   toFile :[ self   getFilePath ]];

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

NSArray * arr = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePath]];



44:  NSUserDefaults储存数据 (储存轻量级的数据(账号 密码  是否登录))
//1.NSUserDefaults 可以存储的数据类型 : NSString  字典  数组  NSNumber BOOL NSData(二进制数据) NSDate(时间) int(integer)  Double   float, URL(网址)
//2.
强制数据及时存储到沙盒
// userDefaults   向沙盒中储存数据     是按照一定的时间戳定时储存数据     如果数据还没来得及存储   而此时程序出现问题   那么数据就会丢失     所以   我们可以同步一下强制数据及时存储到沙盒

//synchronize   同步     保证数据及时的储存到沙盒中
[userDefaults synchronize];

 


45: NSUserDefaults  存取文件
//存数据: 
[[NSUserDefaults standardUserDefaults]setObject:_nameField.text forKey:@"name"];
[[NSUserDefaults standardUserDefaults]setObject:_pswField.text forKey:@"psw"];
       
//同步数据
[[NSUserDefaults standardUserDefaults]synchronize];

//取数据:
NSString * nameString =  [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
NSString * pswString  =[[NSUserDefaults standardUserDefaults]objectForKey:@"psw"];



46:判断某路径下是否存在文件 是不是文件夹    关键词 :fileExistsAtPath

NSString *filePath1 =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/str.plist"];
    NSString *filePath2 =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/ABC"];
    BOOL isDirectory ;
    BOOL isExist= [[NSFileManager defaultManager] fileExistsAtPath:filePath2 isDirectory:&isDirectory];
    if (isExist==YES) {
        NSLog(@"存在文件");
        if (isDirectory==YES) {
            NSLog(@"是个文件夹");
        }else{
            NSLog(@"不是文件夹");
        }
    }else{
        NSLog(@"不存在文件");
    }


47 .网络请求中网络超时设置 
request .timeoutInterval = 10;



48. 单元格关键控件摘要 

1.分割线颜色 样式 :

tableVew .separatorColor =[UIColor redColor];

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 =[_tableView   indexPathForCell :cell];

9.
区头区尾相关内容
//也需要重用 
区头和区尾的设置中 相关的控件设置和添加需要放在   cell. contentView  
e.g:
1.cell.
contentView   . backgroundColor   = [ UIColor   grayColor ];
2.[cell.
contentView   addSubview :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" , @"#" ,];

索引调用的方法:
-(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 . text   base64EncodedString]   编码  
[_nameField . text   base64DecodedString]   解码

[_pswField.text MD5] 加密



54.在web请求体重  截取某个字段

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

NSRange range =[request.URL .absoluteString rangeOfString:@"code="];

NSString * code =[[request.URL.absoluteString componentsSeparatedByString:@"="lastObject];

都是单纯地字符串操作



55.判断授权token 和 过期时间的两种方式 : 
//方式1:
    NSString * token =[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    NSDate * time =[[NSUserDefaults standardUserDefaults] objectForKey:@"time"];
    if (token == nil || [token isEqualToString:@""]) {
        return NO;
    }
    if ([[NSDate date]compare:time] != NSOrderedAscending) {
        return NO;
    }
    return YES;
    
    //方式2:
    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    //过期时间
    NSDate * date = [[NSUserDefaults standardUserDefaults]objectForKey:@"date"];
    if (token == nil || [token isEqualToString:@""]) {
        return NO;
    }
    //当前时间
    NSDate * currentDate =[NSDate date];
    //当前时间和过期时间 对比
    if ([[currentDate laterDate:date]isEqualToDate:currentDate]) {
        return NO;
    }
    return YES;



56.如果需要设置多个tag值时
//
一般设置 tag   只需要设置为数字进行区分的话 就可以 但是如果接口较多 需要区分的话 单独的设置为数字 时间久的话 不好辨认 所以我们可以模仿系统  来写出一个枚举来

// NSInteger   指的是枚举中值的类型   RequestType   总的请求类型
typedef   NS_ENUM (NSInteger, RequestType) {
    GetTokenRequestTag = 0,
    GetStatusListRequestTag
    //需要再往下写的时候  不需要设置数字就可以 因为系统会自动递增  
};

调用时   :
view .tag =   GetTokenRequestTag;



57.向上取整

//首先可以先获取矩形高度 然后向上取整
    CGRect rect =[string boundingRectWithSize:CGSizeMake(310, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17]} context:nil];
    //向上取整
    return ceilf(rect.size.height);


    
58.查找某个具体文件(eg:图片)路径的方法
NSString * directoryPath =[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/ImageCache"];
    //保证沙盒中的Documents 中一定有一个ImageCache 文件夹
    if (![[NSFileManager defaultManager]fileExistsAtPath:directoryPath]) {
        [[NSFileManager defaultManager]createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //把图片的地址字符串分割 最后一个/ 之后的那段就是图片的名字
    NSString * fileName =[[@"URLString" componentsSeparatedByString:@"/"] lastObject];
    NSString * filePath =[NSString stringWithFormat:@"%@/%@", directoryPath, fileName];
    return filePath;



59.在导航条上添加UI控件  

self.navigationItem.titleView = segment;


60.视图留白 

self.automaticallyAdjustsScrollViewInsets = NO; 


61.iOS汉字转为拼音

//城市列表  通讯录  右边索引 字母或者拼音如何的到

NSMutableString * hanzi =[[NSMutableString alloc] 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 按钮设置背景图片时 设置背景图片大小 防止图片变形 
UIImage *btnImg =[UIImage imageNamed:[NSString stringWithFormat:@"button_table_%d",i]];
    UIImage * bbImg =[btnImg stretchableImageWithLeftCapWidth:100 topCapHeight:100];
    [btn setBackgroundImage:bbImg forState:UIControlStateNormal];


64: 异常崩溃处理

 在AppDelegate .m 文件

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //输出模拟器类型
    NSLog(@"%@",[[UIDevice currentDevice]model]);
    //绑定扑捉异常的函数 当程序崩溃时 会先调用这个函数
    NSSetUncaughtExceptionHandler(&getException);
    return YES;
}

void getException(NSException *exception){
    //遇到特殊情况时 需要把异常的具体信息获取并储存
    NSLog(@"名字----%@",exception.name);
    NSLog(@"原因----%@",exception.reason);
    NSLog(@"用户信息----%@",exception.userInfo);
    NSLog(@"栈内存地址----%@",exception.callStackReturnAddresses);
    NSLog(@"栈描述----%@",exception.callStackSymbols);
    NSString *string = [NSString stringWithFormat:@"名字%@,原因%@,信息%@,栈内存地址%@,栈描述%@",exception.name,exception.reason,exception.userInfo,exception.callStackReturnAddresses,exception.callStackSymbols];
    
    NSLog(@"%@",string);
    NSDate *date = [NSDate date];
    
    //当前的系统版本号
    NSString * version =[[UIDevice currentDevice]systemVersion];
    
    //当前设备型号
    [[UIDevice currentDevice]model];
    
    //储存崩溃信息
    
    NSString * path =[NSHomeDirectory()stringByAppendingPathComponent:@"Library/exception.txt"];
    [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    //当程序再次启动时 把崩溃信息发送给服务器
}



65: 去除掉首尾的空白字符和换行字符 

NSString * headerData = [headerData stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
    headerData = [headerData stringByReplacingOccurrencesOfString:@"/r" withString:@""];
    headerData = [headerData stringByReplacingOccurrencesOfString:@"/n" withString:@""];


66:为视图view自定义矩形大小 

self.edgesForExtendedLayout = UIRectEdgeNone;
    CGRect viewBounds = self.view.bounds;
    float navBarHeight = self.navigationController.navigationBar.frame.size.height + 20;
    viewBounds.size.height = ([[UIScreen mainScreen] bounds].size.height) - navBarHeight;
    self.view.bounds = viewBounds;



你可能感兴趣的:(iOS)