iOS 初学者功能代码大集合,个人笔记


UitableView

cell 高度自适应

Masonry





UILabel


 iOS  UI控件

1.UIButton按钮

2.UILabel文本标签

3.UITextField文本输入框

4.UIImageView图片显示

5.UIProgressView进度条

6.UISegmentControl选项卡

7.UIActivityIndicator圈圈,菊花

8.UIAlertView对话框(中间弹框)

9.UIActionSheet底部弹窗

10.UIScrollView滚动的控件

11.UISwitch开关

12.UISlider滑块

13.UIPageControl分页控制

14.UITextView能滚动的文字显示控件

15.UITableView表格

16.UIPickerView选择器

17.UIDataPicker日期选择器

18.UIWebView网页控制

19.UIToolbar工具条

20.UINavigationBar导航条

21.UICollectionView九宫格

模拟器:界面布局查看工具:reveal

====================================================================================



Reveal使用

1. Build Settings 搜索Other

Other Linker Flags设置为 -ObjC

2. Reveal.framework拖到项目中即可


~/资源库/Caches/

找到com.ittybittyapps.Reveal文件夹删除

~/资源库/Preferences/

找到com.ittybittyapps.Reveal.plist删除

又可以使用30


图片自动补充:ksimageNamed

注释带智能提示:WDocumenter





    

    return YES;



UILabel设置多种字体、颜色

   NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String,try your best to test attributed string text"];

    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];

    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];

    [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];

    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:30.0] range:NSMakeRange(0, 5)];

    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:30.0] range:NSMakeRange(6, 12)];

    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:30.0] range:NSMakeRange(19, 6)];

    

    UILabel *attrLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 320 - 40, 90)];

    attrLabel.attributedText = str;

    attrLabel.numberOfLines = 0;

    [self.view addSubview:attrLabel];

iOS 调试方法

po _image  可以看到_imge 的信息

模拟器安装app

xcrun simctl install booted +APP的路径

文本框键盘遮挡问题


UINavigationControllerDelegate

 _niChenText.delegate=self;



[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];

    

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];

@property (strong,nonatomic)UITextField *SelectTextField;


///键盘显示事件

- (void) keyboardWillShow:(NSNotification *)notification {

    

    //获取键盘高度,在不同设备上,以及中英文下是不同的

    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;

    

    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)

    CGFloat offset = (_SelectTextField.frame.origin.y+_SelectTextField.frame.size.height+50) - (self.view.frame.size.height - kbHeight);

    

    // 取得键盘的动画时间,这样可以在视图上移的时候更连贯

    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    

    //将视图上移计算好的偏移

    if(offset > 0) {

        [UIView animateWithDuration:duration animations:^{

            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);

        }];

    }

}


///键盘消失事件

- (void) keyboardWillHide:(NSNotification *)notify {

    // 键盘动画时间

    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    

    //视图下沉恢复原状

    [UIView animateWithDuration:duration animations:^{

        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

    }];

}

- (void)textFieldDidBeginEditing:(UITextField *)textField{

    _SelectTextField=textField;

}


-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

    [textField resignFirstResponder];

    return YES;

}


图片拉神

 UIImage * resizeImage=[normal resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w)];

//        resizeImage stretchableImageWithLeftCapWidth:<#(NSInteger)#> topCapHeight:<#(NSInteger)#>];



背景单击事件

@interface LCTianJianDiZhiController ()<HZAreaPickerDelegate,UIGestureRecognizerDelegate>

   UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backGroundOnclick)];

    tapGestureRecognize.delegate = self;

    [self.view  addGestureRecognizer:tapGestureRecognize];

-(void)backGroundOnclick

{

    [_selectDiQu setTitle:@"选择" forState:UIControlStateNormal];

    [self.view endEditing:YES];

    [self cancelLocatePicker];

    

}

以下情况不能交互

alpha<0.01

hidden=yes

userInteracion=no 

父视图不允许交换,子视图也不能

在父图可见范围内可以交换,范围之外不能交互



UiImageView 默认不允许用户交互


uitableviewcell 点击没有效果

 cell.selectionStyle = UITableViewCellSelectionStyleNone;

隐藏导航栏

[self.navigationController setNavigationBarHidden:YES animated:NO];

隐藏标签栏

self.tabBarController.tabBar.hidden =YES;

时间戳转换为时间

 NSString *str=[_mydata[indexPath.row]valueForKey:@"appr_comment_time"];//时间戳

    NSTimeInterval time=[str doubleValue]/1000+28800;//因为时差问题要加8小时 == 28800 sec

    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];

    NSLog(@"date:%@",[detaildate description]);

    //实例化一个NSDateFormatter对象

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    //设定时间格式,这里可以设置成自己需要的格式

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    

    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];

    NSLog(@"%@",currentDateStr);

密码文本框secureTextEntry

把数据存储到本地

存储

//获取userDefault单例

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

        

        //登陆成功后把用户名和密码存储到UserDefault

        [userDefaults setObject:_userName.text forKey:@"name"];

        [userDefaults setObject:_password.text forKey:@"password"];

        [userDefaults synchronize];


调用

//获取UserDefault

    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

    _userName.text= [userDefault objectForKey:@"name"];

    _password.text= [userDefault objectForKey:@"password"];

页面切换的方式

从一个ViewController切换到另一个ViewController有下面几种方法:

1addsubview方法切换视图

         self.view addSubview:(加载的新页面);

     相应的 [self.view removeFromSuperview];移除添加的view

2self.view insertSubview:(加载的新页面) atIndex:n;

n的解释:页面都是层次叠加的,n表示加载到那一层上面


3presentModalViewController方法

        photoNacController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

     photoNacController.modalPresentationStyle = UIModalPresentationFullScreen;

    self presentModalViewController:(加载的新页面) animated:

    modalTransitionStyle用于设置页面切换的动画

     modalPresentationStyle用于设置视图显示的方式

         两种方法试试就知道用途了!

(4) pushViewController导航

       [self.navigationController pushViewController:(加载的新页面animated:YES];

      对应的

        [self.navigationController popViewControllerAnimated:YES];

总结:系统提供了我们视图切换的方法以及视图切换的默认动画,我们可以选择这几种方法中的去使用,也可以自定义切换的动画animation,我知道的就这些大家有别的欢迎评论我,我重新整理这篇文章


/** 隐藏状态栏 */

- (BOOL)prefersStatusBarHidden

{

    return YES;

}

    // 调整边距,可以让表格视图让开状态栏

    self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);


代删除线的UILabel

- (void)drawRect:(CGRect)rect {

    // Drawing code

    [super drawRect:rect];

    CGContextRef context=UIGraphicsGetCurrentContext();

    CGContextMoveToPoint(context, 0, 8);

    CGContextAddLineToPoint(context, rect.size.width, rect.size.height-5);

    CGContextStrokePath(context);

}

从xib加载时如果不显示或出错就可能是伸缩的问题

dropdown.autoresizingMask=UIViewAutoResizingNone;


unbutton 设置圆角边框

[huoQuYanZhenMa.layer setMasksToBounds:YES];

    [huoQuYanZhenMa.layer setCornerRadius:10.0]; //设置矩形四个圆角半径

    [huoQuYanZhenMa.layer setBorderWidth:1.0]; //边框宽度

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 1, 0, 0, 1 });

    [huoQuYanZhenMa.layer setBorderColor:colorref];//边框颜色

    [self.view addSubview:huoQuYanZhenMa];

界面跳转

- (void)pushAction{

    PushViewController *pushVC = [[PushViewController alloc] init];

    [self.navigationController pushViewController:pushVC animated:YES];

    RootViewController *rootVC = (RootViewController *)self.tabBarController;

    [rootVC showTabBar:NO];

    //[self.navigationController showViewController:<#(UIViewController *)#> sender:<#(id)#>]

}

- (void)presentAction{

    ModalViewController *modalVC = [[ModalViewController alloc] init];

    //模态视图

    [self presentViewController:modalVC animated:YES completion:nil];

}

- (void)dismissAction{

    [self dismissViewControllerAnimated:YES completion:nil];

}

- (void)popAction{

    [self.navigationController popViewControllerAnimated:YES];

}



UIStoryboard *stryBoard=[UIStoryboard storyboardWithName:@"Main" bundle:nil];


        [self presentViewController:[stryBoard instantiateViewControllerWithIdentifier:@"mytabBarContol"] animated:NO completion:nil];

语法约定

方法首字母大小,单词切换用大写

类名要大写

初始化应用要initW~~,w一定要大些,并且前面一定是init才行;不然self=[super init]会出错

 打印结构体

NSLog(@“%@”,nSStringFromRange(range));

代理的作用

监听哪些不能用addTarget监听的事件

主要用来负责两个对象之间的消息传递

代理实现的步骤

(1)成为(子)控件的代理,父亲(控制器)成为儿子(文本框)的代理

(2)遵守协议,利用智能提示具体实现

代理的id应该用weak 弱引用,不然会照成循环引用

判断是否实现某个协议方法

if ([self.delegate respondsToSelector:@selector(tgFooterViewDidDowenLoadButton:)]) {

            [self.delegate tgFooterViewDidDowenLoadButton:self];

        }


代理模式:是父控件(视图控制器)监听子控件的事件,当子控件发生某些事情时通知父控件工作

footerView->controller 去工作,用代理

conterView->footerView去工作,直接调用用footView的方法


不要分割线

    tabQQChat.separatorStyle=UITableViewCellSeparatorStyleNone;


内边距


_textView.contentEdgeInsets=UIEdgeInsetsMake(20, 20, 20, 20);


获取文本的宽高

 //3.正文

    CGFloat textX;

    CGFloat textY=iconY;

    CGSize textmaxSize= CGSizeMake(150, MAXFLOAT);

    CGSize textRealSizw=[message.text boundingRectWithSize:textmaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0f]} context:nil].size;

模型中数据中文乱码

//对象描述方法,类似toStrong

-(NSString *)description

{

    return [NSString stringWithFormat:@"=<%@:   %p>{answer: %@,icon:%@,title:%@,option:%@}",self.class,self ,self.answer,self.icon,self.title,self.options];

    

}

然后在viewDidLoad

   NSLog(@"%@",self.question);

//    for (Question *obj in self.question) {

//        NSLog(@"%@",obj);

//    }

然后导入NSArray+Log.h

改变状态栏的颜色

-(UIStatusBarStyle)preferredStatusBarStyle

{

    return UIStatusBarStyleLightContent;

}

隐藏返回按钮文字

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)

 forBarMetrics:UIBarMetricsDefault];

uitableVIew的背景图片

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"leftMenu.jpg"]];

    self.tableView.backgroundView = imageView;

分割线

self.tableView.separatorStyle=UITableViewCellSeparatorStyleLSingleLine;

删除多余的分割线

//删除多余的分割线


    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];//tableView删除多余的分割线

- (void)setExtraCellLineHidden: (UITableView *)tableView

{

    

    UIView *view = [UIView new];

    

    view.backgroundColor = [UIColor clearColor];

    

    [tableView setTableFooterView:view];

}

Cell中的代理方法

/** 

 初始化方法

 

 使用代码创建Cell的时候会被调用,如果使用XIB或者Storyboard,此方法不会被调用

 */

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier



/**

 XIB被加载之后,会自动被调用,如果使用纯代码,不会被执行

 */

- (void)awakeFromNib


 Cell 被选中或者取消选中是都会被调用

 

 如果是自定义Cell控件,所有的子控件都应该添加到contentView

 */

- (void)setSelected:(BOOL)selected animated:(BOOL)animated


注释代码

如果是0,就注释,1就不注释

#if 0

#endif


颜色的问题:

32位真彩色ARGB

24位真彩色RGB


UIView的常用方法:

-(void)addSubview:(UIVIew *)view;添加一个子控件

-(void)removeFromSuperview; 从父控件中移除

-(UIView *)viewWithTag:(NSInteger)tag;根据tag表示寻找到对应的控件(一般是用于寻找子控件)


加载xib文件:

NSArray *array=[[NSBundle mainBundle] loadNibName:@“HMAppView”owne:nil  options:nil];

UIView *view=[array firstObject];

计算给定文本字符串


UILabel要换行就要给设置行为0;

_textView.numberOfLines=0;

// boundingRectWithSize计算给定文本字符串所占的区域

    // 返回值是一个x,y = 0CGRect,w,h是计算好的宽高

    //

    // 如果要计算多行的准确高度,需要传入NSStringDrawingUsesLineFragmentOrigin选项

    // dict用于指定字体的相关属性的字典,UIKit框架中的第一个头文件

    // context: nil

    NSDictionary *nameDict = @{NSFontAttributeName: kNameFont};

    CGRect nameFrame = [self.status.name boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:nameDict context:nil];

    nameFrame.origin.x = CGRectGetMaxX(self.iconView.frame) + padding;

    nameFrame.origin.y = padding + (self.iconView.bounds.size.height - nameFrame.size.height) * 0.5;

    self.nameView.frame = nameFrame;



调用函数:

等待一段时间 延时

[self performSelector:@selector(cleanup) withObject:nil afterDelay:self.tom.animationDuration];//tom动画中用到的

设置常用代码块:

<#view#>.backgroundColor=[UIColor  <#color #>];

 


代码块存放路径:

/Users/a625/Library/Developer/Xcode/UserData/CodeSnippets


uitableview继承自uiscrollview

需要知道共有多少行,每一行有多高才能计算出UIscrollview的高度

知道每一行的高度,就可以计算出每一个屏幕显示多数航,才计算出表格明细方法的执行次数


tableview .rowhight 的效率比代理更高,如果行高一样就用属性,不一样用代理

修改控件大小:


-(IBAction)top:(UIButton *)sender{

CGRect btnFrame=self.HeadBtn.Fram;

btnFrame.origin-=10;

self.headBtn.fram=btnFrame;

}

下面代码错误的,oc规定不允许直接修改对象的结构体属性的成员

self。headBtn.frmae.origin.y-=10;

代码创建按钮:

1.创建一个自定义的按钮

UIButton *btn=[UIButton buttonWithTypeCustom];

2.添加按钮

[self.view addSubview:btn];

3.设置按钮的位置和尺寸

btn.frame=CGRectMake(100,100,100,100);

4.监听按钮的点击事件(点击按钮后就会调用self的btnClick方法)

[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];

5.设置按钮在在默认状态下的属性

5.1默认状态下的背景

[btn setBackgroundImage:[UIImage imageName@“btn_01”] forState:UIControlStateNormal];

5.2.设置默认状态下的文字://千万不要用btn.titleLabel.text=@“sdsd”;

[btn setTitle:@“点我啊”forState:UIControlStateNormal];

5.3 默认状态的文字颜色

[btn setTitleColor:[UIColor redColor]forState:UIControlStateNormal];

6.设置按钮在高亮状态下的属性

6.1 高亮状态的背景

[btn setBackgroupImage:[UIImage imageName:@“btn_01”] forState:UIControlStateHighlighted];

6.2 高亮状态下的文字颜色

[btn setTitle:@“摸我干啥”forState:UIControlStateHighlighted];

6.3 高亮状态下文字颜色

[btn setTitleColor:[UIColor blueColor] forState:UIControlStateHightlighted];

修改按键的字体(titleLabel 是只读的  readonly 表示不允许修改titleLabel的指针)

btn.titleLabel.font=[UIFont sysTemFontOfsize 13];



sender.currentTitle //取出当前按钮的标题文字

CGRectGetMaxY(lable.frame);



frame属性,一般不要修改,通常用于实例化控件,指定初始位置

如果需要改变控件大小,使用bounds 

如果需要改变控件位置,使用center


@property

1.生成getter()方法

2.生成setter() 方法

3生成带下划线的成员变量(纪录属性内容)

readonly的属性不会生成带下划线的成员变量

 @synthesize 可以合成出来 @synthesize image=_image;

代理的相关

1.遵守相关的协议,预先定义好方法,具体的实现工作有代理负责

<控件名称+DataSource> 定义的数据有关的方法

<控件名称+Delegate> 定义的与事件有关的方法,通常用来监听控件事件的

2.代理方法

1> 方面名以控件名称开口(没有前缀) ->方便程序员编写的时候快速找到需要的方法

2> 第一个参数是自己 ->意味着在协议方法中可以直接访问对象的属性,或者调用方法

3>代理方法的返回值 ->控制器向控件(委托)发送数据

内存管理:

控件:

如果是托线,用Weak

如果是代码,用Strong

NString 用copy

数字型的int 使用Assign


图片:

JPG:压缩比较高,通常用于照片,网页,有损压缩,解压缩时 对cpu消耗大,意味慢,费电

PNG: 压缩比高,无损压缩,

uiscrollView

    self.scrollView.contentInset=UIEdgeInsetsMake(20, 20, 20, 20);

    self.scrollView.showsHorizontalScrollIndicator=NO;

    self.scrollView.showsVerticalScrollIndicator=NO;

    //偏移位置

    self.scrollView.contentOffset=CGPointMake(100, 100);

    self.scrollView.bounces=NO;//取消弹簧效果



 contentSize    会根据边距调整offset

 contentInset   不会调整offset

主意两者的顺序

动画的两种方式:

1.头尾式

[UIView beginAnimations:nil context:nil];

/**需要执行的动画**/

[UIViewcommitAnimations];

2.Block式

[UIView animateWithDuration:0.5 animations:^{

/**需要执行动画的代码**/

}];


修改控件的位置和尺寸:

位置

frame.origin 原点

center      中心

尺寸:

frame.size

bounds.sizes

查看是否调用该函数

NSLog(“@”__func__);

get方法中

,如果跟自己相关的用下划线,不相干的用self


字典转模型

-(NSArray)appList

{

if(appList==nil)

{

NSArray *array=[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] PathForResouce:@“app.plist” ofType:nil]];

//创建一个临时数组

NSMutableArray *arrayM=[MSMutableArray array];

for(NSDictionary *dict in array)

{

HMAppInfo *appInfo=[[HMAppInfo alloc]init];

appInfo.name=dict[@“name”];

appInfo.icon   =dict[@“icon”];

[arrayM oddObject:appInfo];


}

//将临时数组复制给属性

_appList=arrayM;

}

return _appList;

}

使用时:

先实例化:HMAppInfo *appInfo=self.appList[i];

再使用: icon.image=[UIImage imageName:appInfo.icon];





uitextView 光标不再最开始位置

 self.automaticallyAdjustsScrollViewInsets = NO;


设置标签栏属性

 

    UITabBarItem*item =self.tabBarController.tabBar.items[0];

    

    UIImage*imageNomal = [[UIImage imageNamed:@"table_zhuye_off"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    item.image= imageNomal;

    

    UIImage*imageSelected = [[UIImage imageNamed:@"table_zhuye_on"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    item.selectedImage= imageSelected;

    

    self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];

    self.tabBarController.tabBar.translucent = false;  //关闭透明

    self.tabBarController.tabBar.tintColor = [UIColor colorWithRed:0.359 green:0.902 blue:0.296 alpha:1.000];



退出键盘

方法一:[self.textfield resigFirstResponder];

方法二:[self.view endEditing:YES];//Yes是否性关闭键盘

transform修改控件的位移(位置),缩放,旋转

创建一个transform属性//相对初始

CGAffineTransForm CGAffineTransformMakeTransLation(CGFloat tx,CGFloat ty);//左右移动

CGAffineTransForm CGAffineTransformMakeScale(CGFloat sx,CGFloat sy);//放大缩小

CGAffineTransForm CGAffineTransformMakeRotaton(CGFloat angle);  //angle是弧度制,,排M_PI_4

 在某个transform的基础上进行叠加

CGAffienTransForm CGAffienTransformTransSlate(CGAffienTransForm t,CGFloat tx.CGFloat ty);

CGAffienTransForm CGAffienTransFormScale(CGAffienTransform t , CGFloat sx,CGFloat sy);

CGAffienTransForm CgAffeinTransformRotate(CGAffienTransform t,CGFloat angle);

清空之前设置的transForm属性

view.transfrom=CGAffineTransformIdentity;


例:

self.butotn.transform=CGAffineTransForMakeTranslation(0,-100);//向上平移100;

NSLog(@“%@”,NSStringFromCGAffineTRansfor(self.button.transform));

self.button.transform=CGAffineTransFormRotate(self.button.transform,-M_PI_4);//逆时针旋转45度

UIImage加载图片:

一个UIImage对象代表了一张图片,一般通过Image:@”图片名“加载图片(png格式的图片可以省略拓展名)

UIImage *image=[UI image imageName:@“btn_01”];

imageNamed :图像是实例化之后由系统 负责,

String *path=[[NSBundle mainBundle] pathForResource:imageName];

可以使用:UIImae *image=[UIImage imageWithContentsOfFile:path];//但是不能放在images.xcassets

解析Plist文件

1.获取Plist文件路径

NSBundle *bundle=[NSBundle MianBundle];

NSString *path=[bundle pathForResource:@“imageData” ofType:@“plist”];

2.懒加载Plist文件

_image=[NSArray arrayWithContentOfFile:path];


-(NSArray *)image

{

if(_image==nil){

NSBundle *bundle=[NSBundle MianBundle];

NSString *path=[bundle pathForResource:@“imageData” ofType:@“plist”];

_image=[NSArray arrayWithContentOfFile:path];

}

return _image;

}

get()懒加载

在get()方法中不要在调用get()方法了,

self.btn是属于get()方法

_btn 是变量名,不属于get()方法

在懒加载中属于get()方法,所有懒加载中不能出现self.btn~ 不然会出现死循环


时钟

    // scheduledTimerWithTimeInterval 方法本质上就是创建一个时钟,

    // 添加到运行循环的模式是DefaultRunLoopMode

    // ----------------------------------------------

    // 1>

//    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:@"hello timer" repeats:YES];

    

    // ----------------------------------------------

    // 2> 1等价

//    self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];

//    // timer添加到运行循环

//    // 模式:默认的运行循环模式

//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];

    

    // ----------------------------------------------

    // 3>

    self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];

    // timer添加到运行循环

    // 模式:NSRunLoopCommonModes的运行循环模式(监听滚动模式)

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];



 // 停止时钟

   [self.timer invalidate];

枚举

    //枚举类型本质上是整数,定义的时候,如果指定了第一个整数值,然后后面的就会递增

//枚举时解决魔法数字的很好工具

typedef enum

KmovingDirTop=10;

KmovingDirBottom;

KmovingDirLeft;

KmovingDirRigth

}KmoingDir;

通知中心传值:

 //发送通知

        [[NSNotificationCenter defaultCenter]postNotificationName:@"categoryDidChanged" object:nil userInfo:@{@"categoryModel":_seletedModel}];

接受:

 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(categoryChange:) name:@"categoryDidChanged" object:nil];

- (void)categoryChange:(NSNotification*)noti{

    CategoriyModel *md = (CategoriyModel*)noti.userInfo[@"categoryModel"];

    NSString *str = noti.userInfo[@"subCategoryName"];

    NSLog(@"左表:%@",md.name);

    NSLog(@"右表:%@",str);

    

}

- (void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

}



uitableviewCell 更新

//一个section刷新    

NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];    

[tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];    

//一个cell刷新    

NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];    

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];  


获取屏幕高度

#define  kScreenWidth   [UIScreen mainScreen].bounds.size.width

#define kScreenHeight   [UIScreen mainScreen].bounds.size.height



生成随机数

arc4random_uniform(10) => 0~9之间的随机数


ARC 编译:

-fno-objc-arc


AFNetworking 的使用:

    

    //1.创建

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    

    //2.指定解析器

//      manager 默认情况下是解析 json plist

//      xml 手动设置

//    manager.responseSerializer

//    manager.requestSerializer

//    aplication/json  text/json

    

    //3.get/post 请求

    //接口地址 urlString

    //请求参数

    //网络请求成功后的回调 blocks

    

    [manager GET:<#(NSString *)#> parameters:<#(id)#> success:^(AFHTTPRequestOperation *operation, id responseObject) {

        //成功后的操作

//        operation.resposeData

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        //请求失败后的操作

        NSLog(@"%@",error);

        

    }];

    

    //post

    [manager POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        //发送后的回调

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        //发送失败后的回调

    }];

    

    // 1. 网络下载数据然后把数据转为图片 再加载

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"image/jpeg"];

    [manager GET:imageURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"下载图片成功!");

        iv.image = [UIImage imageWithData:operation.responseData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"%@",error);

    }];




-(void)download{

//&tag=1001011&telephone=18398850943&password=111111

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //manager.requestSerializer = [AFHTTPRequestSerializer serializer];

    [manager GET:@"http://120.25.160.35:8080/LocalGoodBrand/UserServlet" parameters:

     @{@"tag"           : @"100111"}

         success:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSString *string=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

             NSData* jsonData=[string dataUsingEncoding:NSUTF8StringEncoding];

             _dataArray=   [NSJSONSerialization

                                JSONObjectWithData:jsonData

                                options:NSJSONReadingMutableContainers

                                error:nil];


             

            

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"Error: %@", error);

    }];

    



}

SDWebImage的使用:

 [iv sd_setImageWithURL:[NSURL URLWithString:imageURL]];


    UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backGroundOnclick)];

    tapGestureRecognize.delegate = self;

    [self.view  addGestureRecognizer:tapGestureRecognize];


删除storyboard

1.删除storyboard 

2.general 中删除“main”

2.info 中删除 storyboard选项

3.屏幕初始化:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    

    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];

    self.window.backgroundColor = [UIColor whiteColor];

    

    //创建导航栏 需要传入一个UICollectionViewController

    FirstViewController *fvc = [[FirstViewController alloc]init];

    MyNavController *nav = [[MyNavController alloc]initWithRootViewController:fvc];

    self.window.rootViewController = nav;//

    [self.window makeKeyAndVisible];

    return YES;

}

iOS各个尺寸:

}屏幕尺寸.png


按钮监听事件:

- (void)addtarget:(id)target action:(SEL)action{

    [self.button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

}

[first addtarget:self action:@selector(firstClick)];

#pragma mark - 点击事件

- (void)firstClick{

    [self createPopver];

}

获取plist文件数据

    //获取plist文件地址

    NSString *file = [[NSBundle mainBundle]pathForResource:@"categories.plist" ofType:nil];

    //加载plist为数组

    NSArray *plistArray = [NSArray arrayWithContentsOfFile:file];

关闭popview 的自动适应屏幕属性:

pop.autoresizingMask = UIViewAutoresizingNone;

屏幕切换动态效果:

nav.modalPresentationStyle = UIModalPresentationFormSheet;

隐藏导航栏;

[self.navigationController setNavigationBarHidden:YES animated:YES];


设置tabbar的初始位置:

 self.selectedIndex=button.1


判断网络连接:

OOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 开启网络指示器

    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    //基准网站

    NSURL *url = [NSURL URLWithString:@"http://baidu.com"];

//    监听结果回调

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];

    NSOperationQueue *operationQueue       = manager.operationQueue;

    

    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        

        switch (status) {

            case AFNetworkReachabilityStatusReachableViaWWAN:

            case AFNetworkReachabilityStatusReachableViaWiFi:

                

                [operationQueue setSuspended:NO];

                

                NSLog(@"有网络");

                

                break;

                

            case AFNetworkReachabilityStatusNotReachable:

            default:

                

                [operationQueue setSuspended:YES];

                

                NSLog(@"无网络");

                

                break;

        }

        

    }];

    

    // 开始监听

    [manager.reachabilityManager startMonitoring];




uiLabel 自动换行和自适应

要想UI Label自动换行,line设置为0

1.N行完全自适应:

        UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];

        NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";

        testLabel.numberOfLines = 0; ///相当于不限制行数

        testLabel.text = txt;

这样不行,还需要调用 [testLabel sizeToFit];



2.限制在N行内自适应:

        UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];

        NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";

        testLabel.numberOfLines = 3;   限制在3行内自适应

        testLabel.text = txt;

     [testLabel sizeToFit];

结果不起作用,全部在一行显示了。


3.为了实现2的需求,需要这么做:

        CGSize maxSize = CGSizeMake(100, 21*3);

        UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];

        NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";

        CGSize labelSize = [txt sizeWithFont:testLabel.font constrainedToSize:maxSize lineBreakMode: UILineBreakModeTailTruncation];


        testLabel.frame = CGRectMake(testLabel.frame.origin.x, testLabel.frame.origin.y, labelSize.width, labelSize.height);

        testLabel.text = txt;


 NSString  

/*_________________________NSString(不可变字符串)___________________________*/

    

        //---------------(1)字符串创建--------------------//

    //创建一个字符串常量

    NSString *string1 = @"hello";

    string1 = @"hello world";

    NSLog(@"%@",string1);

    

    //创建字符串

    NSString *string2 = [[NSString alloc] initWithString:@"hello"];

    //initWithFormat:多个字符串拼接

    NSString *string3 = [[NSString alloc] initWithFormat:@"hello %@",string2];

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

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

    

    NSString *ss1 = [[NSString alloc] initWithFormat:@"ZHANGsan"];

    NSString *ss2 = [[NSString alloc] initWithFormat:@"zhangsan"];

    NSLog(@"[ss1 caseInsensitiveCompare:ss2]:%ld",[ss1 caseInsensitiveCompare:ss2]);

    

    //创建空的字符串

    NSString *string4 = [[NSString alloc] init]; //等价于string4 = @"";

    

    //stringWithFormat:使用类方法创建字符串对象

    //NSString *string5 = [NSString stringWithString:@"hello"];  //等价于string5 = @"hello";

    NSString *string6 = [NSString stringWithFormat:@"hello %@",@"world"];

    

    //使用格式化符拼接数值

    int number = 101;

    NSString *string7 = [NSString stringWithFormat:@"class:%d",number];

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

    

    //---------------(2)字符串的比较--------------------//

    NSString *s0 = @"无限互联";

//    NSString *s11 = @"无限互联";   //s0s11的指针地址是一样的,指向的都是常量区同一个字符串对象

    

    NSString *s1 = [NSString stringWithFormat:@"无限互联"];

    NSString *s2 = [[NSString alloc] initWithFormat:@"无限互联"];

    //判断s1s2的指针地址是否相等

    if (s0 == s2) {   //不相等,因为是两个对象,指针地址不一样

        NSLog(@"s0 == s2");

    }

    

    //isEqualToString: 是比较两个字符串内容是否相同

    if ([s0 isEqualToString:s2]) {

        NSLog(@"s0s2的字符串内容相同");

    }

    NSObject *obj1;

    NSObject *obj2;


    NSString *string8 = @"a";

    NSString *string9 = @"A";

    //compare: 比较字符串的大小

    NSComparisonResult result = [string8 compare:string9];

    if (result == NSOrderedAscending) { //结果为升序

        NSLog(@"string8 < string9");

    } else if(result == NSOrderedSame) {

        NSLog(@"string8 string9 内容一样");

    } else if(result == NSOrderedDescending) {

        NSLog(@"string8 > string9");

    }

    

    //---------------(3)字符串的其他用法--------------------//

    //length: 获取字符串的长度

    NSString *string10 = @"abcdef";

    NSInteger len = [string10 length];

    NSLog(@"len = %ld",len);

    

    NSString *string11 = @"hELlo";

    //uppercaseString:将字符串中的字母转成大写

    NSLog(@"upper:%@",[string11 uppercaseString]);

    //uppercaseString

    NSLog(@"lower:%@",[string11 lowercaseString]);

    //capitalizedString:首字母大写,其他字母小写

    NSLog(@"capitalized:%@",[string11 capitalizedString]);

    

    //将字符串转成基本数据类型

    NSString *string12 = @"3.14";

    //float f = (float)string12;  //错误

    //floatValue:字符串中是一个浮点数值转成float

    float f = [string12 floatValue];

    NSLog(@"floatValue:%f",f);

    

    NSString *string13 = @"1";

    BOOL bo = [string13 boolValue];  //true

    

    //---------------(4)字符串截取--------------------//

    NSString *string14 = @"abcdef";

     //---------------(4)字符串截取--------------------//

    NSString *substring1 = [string14 substringToIndex:3];

    NSLog(@"substringToIndex:%@",substring1);

    

    //substringFromIndex:从指定索引位置开始截取到末尾,包含指定的索引f

    NSString *substring2 = [string14 substringFromIndex:1];

    NSLog(@"substringFromIndex:%@",substring2);

    

    NSRange rang = {2,3};  //2:指定位置  3:需要截取的长度

    //substringWithRange:截取指定范围的字符串

    NSString *substring3 = [string14 substringWithRange:rang];

    NSLog(@"substringWithRange:%@",substring3);



NSArray *array = [string componentsSeparatedByString:@"A"]; //从字符A中分隔成2个元素的数组

    

    

    //---------------(5)拼接字符串--------------------//

    NSString *str1 = @"Hello";

    NSString *str2 = @"World";

    NSString *str3 = @"OC!";

    NSString *string15 = [NSString stringWithFormat:@"%@-%@-%@",str1,str2,str3];

    NSLog(@"string15:%@",string15);

    

    //字符串追加

    NSString *string16 = [string15 stringByAppendingString:@"-iOS"];

    NSString *string17 = [string15 stringByAppendingFormat:@"%@,%@",@"iOS",@"iPhone"];

    NSLog(@"string16:%@",string16);

    NSLog(@"string17:%@",string17);

    

    //字符串追加

    NSString *link = @"www.iphonetrain.com/.html";

    //rangeOfString:查找字符串所在的位置

    NSRange linkRang = [link rangeOfString:@"html"];

    if (linkRang.location != NSNotFound) {

        NSLog(@"location:%ld,length:%ld",linkRang.location,linkRang.length);

    }

    

    //例如:能查找到@163.com,说明此邮箱是网易邮箱

    //NSString *email = @"12345@163.com";

    

/*___________________________NSMutableString(不可变字符串)__________________________*/


    //NSMutableString *mutableString1 = @"string";  错误

    

    NSMutableString *mutableString1 = [[NSMutableString alloc] initWithFormat:@"字符串"];

    //insertString: 在原有的字符串基础上插入字符串

    [mutableString1 insertString:@"可变" atIndex:0];

    NSLog(@"mutableString1:%@",mutableString1);

    

    NSMutableString *mutableString2 = [NSMutableString stringWithFormat:@"字符符符串"];

    //rangeOfString:查找指定字符串所在的范围

    NSRange rang3 = [mutableString2 rangeOfString:@"符符"];

    //deleteCharactersInRange:根据范围删除指定的字符串

    [mutableString2 deleteCharactersInRange:rang3];

    NSLog(@"mutableString2:%@",mutableString2);

    

    NSMutableString *mutableString3 = [NSMutableString stringWithFormat:@"字符串"];

    NSRange rang4 = [mutableString3 rangeOfString:@"字符"];

    //replaceCharactersInRange:withString:  字符串替换

    [mutableString3 replaceCharactersInRange:rang4

                                  withString:@"羊肉"];

    NSLog(@"mutableString3:%@",mutableString3);

    



NSArray   

/*_________________________不可变数组(NSArray)_______________________________*/

    

    //---------------------1.数组的创建--------------------------//

    NSString *s1 = @"zhangsan";

    NSString *s2 = @"lisi";

    NSString *s3 = @"wangwu";

    

    NSArray *array1 = [[NSArray alloc] initWithObjects:s1,s2,s3, nil];

    NSLog(@"%@",array1);

    

    //类方法创建,注意:最后以nil结尾。

    NSArray *array2 = [NSArray arrayWithObjects:s1,s2,s3, nil];

    //初始一个元素对象

    NSArray *array3 = [NSArray arrayWithObject:s1];

    

    //创建一个数组,此数组中的元素来自array1

    NSArray *array4 = [NSArray arrayWithArray:array1];

    

    //---------------------2.通过下标取元素--------------------------//

    NSString *str1 = [array4 objectAtIndex:0]; 

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

    

    //---------------------3.数组的元素个数--------------------------//

    NSUInteger count = [array4 count];

    NSUInteger count2 = array4.count;  //点语法等价于-> [array4 count];//注意count是不能带参数

    NSLog(@"count2 = %ld",count2);

    

    //---------------------4.判断是否包含某个对象--------------------------//

    BOOL isContains = [array4 containsObject:@"zhangsan"];

    NSLog(@"isContains: %d",isContains);

    

    //---------------------5.对象在数组中的索引位置--------------------------//

    NSUInteger index = [array4 indexOfObject:@"wangwu"];

    NSLog(@"index = %ld",index);

    

    //---------------------6.链接数组中的字符串--------------------------//

    //注意:数组中的元素必须都是字符串,才可以使用此方法

    NSString *joinString = [array4 componentsJoinedByString:@","];

    NSLog(@"join:%@",joinString); //zhangsan,lisi,wangwu

    

    //---------------------7.访问最后一个元素--------------------------//

    NSString *last = [array4 lastObject]; //等价于点语法:array4.lastObject;

    NSLog(@"last:%@",last);

    

    //---------------------8.在原来的数组上追加对象--------------------------//

    //追加之后,创建了一个新的数组

    NSArray *array5 = [array4 arrayByAddingObject:@"zhaoliu"];

    NSLog(@"array5:%@",array5);

    

    /*

     注意:1.数组中不能存放基本数据类型,只能存放对象

          2.数组越界

     */

//    NSArray *array6 = [NSArray arrayWithObject:100];  //错误,基本数据类型不能存放到数组中

    

    int idx = 4;

    if (idx < array5.count) {  //严谨的写法,只有下标小于元素个数时,才可以使用下标取元素

        [array5 objectAtIndex:idx];

    }

    

    

    //---------------xcode4.4以后对数组的创建和访问,语法上做了优化---------------//

    //1.创建一个数组

    NSArray *array7 = @[s1,s2,s3];

    //等价于NSArray *array2 = [NSArray arrayWithObjects:s1,s2,s3, nil];

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

    

    NSString *str = array7[0];

    NSLog(@"array7[0] = %@",str);

    

    

/*_________________________可变数组(NSMutableArray)_______________________________*/


    NSString *t1 = @"zhangsan";

    NSString *t2 = @"lisi";

    NSString *t3 = @"wangwu";

    

    //---------------------1.创建可变数组--------------------------//

    NSMutableArray *marray1 = [[NSMutableArray alloc] initWithObjects:t1,t2,t3, nil];

    

    //创建数组时,开辟3个空间来存储元素,当存储的元素超过3个时,系统会自动增大此数组的空间

    NSMutableArray *marray2 = [[NSMutableArray alloc] initWithCapacity:3];

    NSMutableArray *marray3 = [NSMutableArray arrayWithCapacity:3];

    

    //新语法创建的是不可变数组

//    NSMutableArray *marray4 = @[s1,s2,s3];  //错误

    

    //---------------------2.添加元素--------------------------//

    [marray2 addObject:s1];

    [marray2 addObject:s2];

    [marray2 addObject:s3];

    

    //marray2中所有的元素全都添加到marray3

    //[marray3 addObjectsFromArray:marray2];

    

    //这是marray2添加到marray3中,marray3则是个二维数组

    //[marray3 addObject:marray2];

    

    

    //---------------------3.插入元素--------------------------//

    [marray2 insertObject:@"赵六" atIndex:0];

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

//    [marray2 insertObject:@"zhaoliu" atIndex:0];  //错误,数组越界

    

    //---------------------4.替换元素--------------------------//

    [marray2 replaceObjectAtIndex:1 withObject:@"zhangfei"];

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

    

    //---------------------5.互换两个元素的位置--------------------------//

    [marray2 exchangeObjectAtIndex:3 withObjectAtIndex:2];

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

    

    //---------------------6.将另外一个数组的所有元素添加到当前数组--------------------------//

    [marray3 addObjectsFromArray:marray2];

    

    //---------------------7.删除元素--------------------------//

/*

    //7.1根据下标删除

    [marray2 removeObjectAtIndex:0];

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

    

    //7.2根据对象删除

    [marray2 removeObject:@"zhangfei"];

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

    

    //7.3删除最后一个元素

    [marray2 removeLastObject];

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

    

    //7.4删除所有元素

    [marray2 removeAllObjects];

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

 */

    

    //---------------------遍历数组--------------------------//

    //1.普通遍历

    /*

    for (int i=0; i<marray2.count; i++) {

        NSString *str = [marray2 objectAtIndex:i];

       // NSString *str2 = marray2[i];

        NSLog(@"%@",str);

    }

     */

    

    //2.快速遍历

    for (NSString *s in marray2) {

        NSLog(@"%@",s);

    }

    //3.

- (void)viewDidLoad

{

    [super viewDidLoad];

    

    // 块代码

    NSArray *array = @[@(1), @(2), @(3), @(4), @(5)];

    

    // 排序

    array = [array sortedArrayUsingComparator:^NSComparisonResult(NSNumber *num1, NSNumber *num2) {


        // 乱序=>一会升序,一会降序

        // 随机

//        arc4random_uniform(10) => 0~9之间的随机数

        int seed = arc4random_uniform(2);

        if (seed) {

            return [num1 compare:num2];

        } else {

            return [num2 compare:num1];

        }

    }];

    

    NSLog(@"%@", array);

}


- (void)sortWith:(NSArray *)array

{

    // 排序

    array = [array sortedArrayUsingComparator:^NSComparisonResult(NSNumber *num1, NSNumber *num2) {

        

        /**

         1 4 5 2

         4 1 5 2

         4 1 5 2

         5 4 1 2

         5 4 1 2

         5 4 2 1

         */

        NSLog(@"%@ %@", num1, num2);

        

        // 升序

        //        return [num1 compare:num2];

        // 降序

        return [num2 compare:num1];

    }];

    

    NSLog(@"%@", array);

}


- (void)arrayWith:(NSArray *)array

{

    int i = 0;

    for (NSNumber *num in array) {

        NSLog(@"%@", num);

        

        if (i == 1) {

            break;

        }

        i++;

    }

    

    // 参数:对象,索引,是否中断

    // 数组的块方法遍历的效率比for in

    [array enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL *stop) {

        NSLog(@"%@", obj);

        

        // idx == 1 退出循环

        if (idx == 1) {

            *stop = YES;

        }

    }];

}




NSDictonary


/*________________________不可变字典(NSDictonary)___________________________*/

    

    //1.字典的创建

    NSArray *array1 = [NSArray arrayWithObjects:@"zhangsan",@"zhangfei", nil];

    NSArray *array2 = [NSArray arrayWithObjects:@"lisi",@"liping", nil];

    

    //第一个元素:key:@“zhang”  value:array1

    //第二个元素:key:@"li"     value:array2

    NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:array1,@"zhang",array2,@"li", nil];

    NSUInteger count = [dic1 count];

    NSLog(@"count:%ld",count);

    

    NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:array1,@"zhang",array2,@"lisi", nil];

    

    //创建字典时,初始化了一个元素

    NSDictionary *dic3 = [NSDictionary dictionaryWithObject:array1 forKey:@"zhangsan"];

    

    //2.获取字典中元素的个数

    NSUInteger count2 = [dic1 count];

    

    //3.获取字典中所有的key

    NSArray *allkeys = [dic1 allKeys];

    NSLog(@"allkeys:%@",allkeys);

    

    //4.获取字典中所有的value

    NSArray *allvalues = [dic1 allValues];

    NSLog(@"allvalues:%@",allvalues);

    

    //5.通过key取得value

    NSArray *array3 = [dic1 objectForKey:@"zhang"];

    NSLog(@"array3:%@",array3);

        

/*________________________字典的新语法___________________________*/

    

    //创建的语法:{"key1":"value1","key2":"value2"};

    //新语法创建字典

    NSDictionary *dic4 = @{@"zhang":array1,@"li":array2};

    NSLog(@"dic4:%@",dic4);

    

    //value的语法:字典["key"]

    NSArray *array4 = dic4[@"zhang"];

    NSLog(@"array4:%@",array4);

    

    //使用字典存储一个工人的信息

    /*

     {

        "name": "zhangsan", //工人的姓名

        "age" : "22"        //工人的年龄

        ...

      }

     */

    NSDictionary *worker = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan",@"name",@"23",@"age", nil];

    

    

/*________________________可变字典(NSMutableDictionary)___________________________*/


    //1.创建一个可变的数组

    NSMutableDictionary *mdic1 = [[NSMutableDictionary alloc] initWithCapacity:3];

    NSMutableDictionary *mdic2 = [NSMutableDictionary dictionaryWithCapacity:3];

    

    //2.添加元素

    [mdic1 setObject:array1 forKey:@"zhang"];

    [mdic1 setObject:array2 forKey:@"li"];

    

    //将字典dic1中的元素添加到此字典中

    [mdic1 addEntriesFromDictionary:dic1];  //注意:相同的key是不能重复添加到字典中

    

    NSLog(@"mdic1:%@",mdic1);

    

    //3.删除

    //根据key删除元素

//    [mdic1 removeObjectForKey:@"zhang"];

    

    //删除多个元素

//    [mdic1 removeObjectsForKeys:@[@"zhang",@"li"]];

//    NSLog(@"mdic1:%@",mdic1);

    

    //删除所有的元素

    //[mdic1 removeAllObjects];

    

    

    //1.第一种方式

    /*

    for (NSString *key in mdic1) {

        NSArray *names = [mdic1 objectForKey:key];

        NSLog(@"names:%@",names);

    }

     */

    

    //2.第二种方式

    /*

    NSArray *keys = [mdic1 allKeys];

    for (int i=0; i<keys.count; i++) {

        NSString *key = [keys objectAtIndex:i];

        NSArray *names = [mdic1 objectForKey:key];

        NSLog(@"names:%@",names);

    }

     */

    

    //3.第三种方式

    //获取枚举对象,枚举对象中存储的是字典里所有的key

    NSEnumerator *enumer = [mdic1 keyEnumerator];

    

    //让枚举对象的游标指向下一个对象

    id key = [enumer nextObject];

    while (key != nil) {

        

        NSArray *names = [mdic1 objectForKey:key];

        NSLog(@"names:%@",names);

        

        key = [enumer nextObject];

    }

    

    

    //数组也可以使用枚举对象遍历

    /*

    NSArray *array = [NSArray array];

    NSEnumerator *enumer2 = [array objectEnumerator];

    */

    

/*________________________字典排序___________________________*/

    

    NSDictionary *sortDic = @{

                                @"zhangsan":@"50",

                                @"lisi":@"90",

                                @"wangwu":@"80",

                                @"zhao6":@"60"

                            };

    

    //对字典中的value进行排序,参数obj1,obj2是字典中的value

    //返回值是排好序的key

    NSArray *sortedKeys = [sortDic keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        

        int v1 = [obj1 intValue];

        int v2 = [obj2 intValue];

        

        if (v1 > v2) {

            return NSOrderedDescending;

        } else if(v1 < v2) {

            return NSOrderedAscending;

        }

        

        return NSOrderedSame;

        

    }];

    

    for (NSString *name in sortedKeys) {

        NSString *score = [sortDic objectForKey:name];

        NSLog(@"name:%@,score:%@",name,score);

    }

NSSet

 //1.NSSet的创建

    NSString *s1 = @"zhangsan";

    NSString *s2 = @"lisi";

    NSSet *set1 = [[NSSet alloc] initWithObjects:s1,s2, nil];

    NSSet *set2 = [NSSet setWithObjects:s1,s2, nil];

    //把数组array中的所有元素,存储到set3

    NSSet *set3 = [NSSet setWithArray:array];

    

    //2.NSSet转成数组

    NSArray *array1 = [set1 allObjects];

    

    //3.返回元素的个数

    NSUInteger count = [set1 count];

    

    //4.从容器中随机取出一个元素

    NSString *string1 = [set1 anyObject];

    

    //5.判断某一个对象是否在NSSet

    BOOL isContains = [set1 containsObject:@"lisi"];

    

    //6.NSSet中不能重复存同一个对象

    

    //数组中是可以存取重复的对象

    NSString *str = @"jack";

    NSArray *array2 = [NSArray arrayWithObjects:str,str, nil];

    NSLog(@"%@",array2);

    

    //NSSet中不能重复存储相同的对象

    NSSet *set4 = [NSSet setWithObjects:str,str, nil];

    NSLog(@"%@",set4);

    

    /*

      NSSetNSArray的区别

     1. 数组是有下标,NSSet是没有下标的

     2. 数组是有序的,NSSet是无序的

     3. 数组是可以重复存储同一个对象,NSSet反之,不能重复存储对象

    */

    

//    NSMutableSet 


NSNumber

    

/*_______________________________NSNumber的使用___________________________________*/

    

    //1.创建NSNumber(包装基本数据类型)

    NSNumber *intNumber = [NSNumber numberWithInt:100];

    NSNumber *floatNumber = [NSNumber numberWithFloat:9.8f];

    NSNumber *longNumber = [NSNumber numberWithLong:145677766666];

    NSNumber *boolNumber = [NSNumber numberWithBool:YES];

    

    NSArray *array = @[intNumber,floatNumber,longNumber,boolNumber];

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

    

    //2.解包

    int intValue = [intNumber intValue];

    float floatValue = [floatNumber floatValue];

    long longValue = [longNumber longValue];

    BOOL boolValue = [boolNumber boolValue];

    

    //3.新语法创建Number对象

    NSNumber *intNumber1 = @12;  //@"123";

    NSNumber *floatNumber1 = @12.0f;

    NSNumber *longValue1 = @19929292992;

    NSNumber *boolValue1 = @YES;

    NSNumber *charValue = @'a';

    

    

/*_______________________________NSValue的使用___________________________________*/

    

    struct WXPoint {

        float x;

        float y;

    };

    

    //1.创建NSValue(包装结构体), NSValueNSNumber的父类

    //注意:结构体不是对象

    NSRange rang = {100,6};

    //NSRange封包

//    NSValue *rangValue = [NSValue valueWithRange:rang];

    //NSPoint封包

//    NSValue *pointValue = [NSValue valueWithPoint:<#(NSPoint)#>];

    

    //将自定义的结构体包装成NSValue对象

    struct WXPoint p = {50,100};

    NSValue *pointValue = [NSValue value:&p withObjCType:@encode(struct WXPoint)];

    

    //2.解包结构体

    struct WXPoint p2;

    [pointValue getValue:&p2];

    

    NSLog(@"x=%f,y=%f",p2.x,p2.y);

    

    

    //3.NSNull对象

    NSNull *n1 = [NSNull null];

    NSNull *n2 = [NSNull null];

    NSArray *arrayNull = @[n1,n2];

    NSLog(@"%@",arrayNull);

    

    for (id item in arrayNull) {

        

        //判断数组中的对象是否为一个NSNull对象,如果是,则过滤掉

        if (item == [NSNull null]) {

            continue;

        }

        

    }

   NSDate: 

/*__________________________NSDate的使用_____________________________*/

    

    //1.创建日期

    NSDate *date1 = [NSDate date];  //创建了一个当前的日期对象

    NSDate *date2 = [[NSDate alloc] init];

    NSLog(@"date2:%@",date2);

    

    //在当前日期的基础上累加一个数值,单位是秒

    //明天

    NSDate *date3 = [NSDate dateWithTimeIntervalSinceNow:24*60*60];

    NSLog(@"date3:%@",date3);

    

    //昨天

    NSDate *date4 = [NSDate dateWithTimeIntervalSinceNow:-24*60*60];

    NSLog(@"date4:%@",date4);


    //1970年上加一个数值,该数值是一个时间戳数值

    NSDate *date1970 = [NSDate dateWithTimeIntervalSince1970:0];

    NSLog(@"date1970:%@",date1970);


    //2.获取日期的时间戳

    NSTimeInterval time1970 = [date1 timeIntervalSince1970];

    NSLog(@"time1970:%f",time1970);

    

    //取得日期对象date3到当前日期时间的数值差

    NSTimeInterval timeNow = [date3 timeIntervalSinceNow];

    NSLog(@"timeNow:%f",timeNow);

    

    

    //3.日期的比较

    //(1)通过日期对象的compare方法进行比较

    NSComparisonResult result = [date3 compare:date1];

    if (result == NSOrderedDescending) {

        NSLog(@"date3 > date1");

    }

    //(2)通过比较时间戳

    if ([date3 timeIntervalSince1970] > [date1 timeIntervalSince1970]) {

        NSLog(@"date3 > date1");

    }    

    

    

/*__________________________NSDateFormatter格式化日期_____________________________*/

    

    //1.日期对象格式化为字符串: 2013-07-29 15:20:59  20130729

    // 日期对象 --> 字符串

    NSDate *nowDate = [NSDate date];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    //设置日期的格式

    [dateFormatter setDateFormat:@"yyyyMMdd HH:mm:ss"];

    //设置时区

    NSTimeZone *timezone = [NSTimeZone timeZoneWithName:@"America/New_York"];

    [dateFormatter setTimeZone:timezone];

    

    //stringFromDate将日期对象格式化为字符串

    NSString *datestring = [dateFormatter stringFromDate:nowDate];

    NSLog(@"格式化之后:%@",datestring);

    

    //2.将字符串格式化成日期对象

    //字符串 ——>日期对象

  

    NSString *string = @"20130729 16:56:05";

    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];

    [dateFormatter2 setDateFormat:@"yyyyMMdd HH:mm:ss"];

    //dateFromString: 将字符串格式化成日期对象

    NSDate *formatDate = [dateFormatter2 dateFromString:string];

    NSLog(@"%@",formatDate);

    

    

    //获取到所有时区的名称

    NSArray *zoneNames = [NSTimeZone knownTimeZoneNames];

    for (NSString *name in zoneNames) {

        NSLog(@"%@",name);

    }

    


    

/*__________________________捕捉异常_____________________________*/

    //创建一个空数组

    NSArray *arr = [NSArray array];

    

    @try {  //有可能出异常的代码块

        //数组越界异常

        [arr objectAtIndex:5];

    }

    @catch (NSException *exception) {

        //如果捕捉到错误,则会执行此处的代码

        NSLog(@"错误:%@",exception);

    }

    @finally {  //@finally是可选的

        //不管有没有捕捉到异常,此处代码都会执行

        NSLog(@"@finally");

    }

 判断协议中方法是否执行:

    //判断wearNeat方法是否在Student类中定义,如果定义了,才调用

    if ([stu respondsToSelector:@selector(wearNeat)]) {

        [stu wearNeat];

    }


归档:数据存储   

/*____________________________第一种形式________________________________*/

        

        /****************对象归档********************/

        //对象------>文件

        

        /*

        NSArray *array = [NSArray arrayWithObjects:@"zhangsan",@"lisi",@"中文", nil];

        //归档保存的文件路径

        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.arc"];

        

        //归档对象

        BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];

        

        if (success) {

            NSLog(@"归档成功");

        }

        */

        

        

        /****************解归档********************/

        

        /*

        //文件----->对象

        //归档保存的文件路径

        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.arc"];

        

        //解归档

        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

        

        for (NSString *s in array) {

            NSLog(@"%@",s);

        }

         */

        

        

/*____________________________第二种形式________________________________*/        

        

        /*

        

        NSArray *array = [NSArray arrayWithObjects:@"zhangsan",@"lisi",@"中文", nil];

        

        //NSMutableData用于存储归档对象中的数据

        NSMutableData *data = [NSMutableData data];

        //创建归档对象

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

        

        //编码数据和对象

        [archiver encodeObject:array forKey:@"array"];

        [archiver encodeInt:100 forKey:@"scope"];

        [archiver encodeObject:@"jack" forKey:@"name"];

        //....

        

        //完成归档,将归档数据填充至data中,此时data中已经存储了归档对象的数据

        [archiver finishEncoding];

        [archiver release];

        

        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"ar.text"];

        //将归档数据写入文件

        BOOL success = [data writeToFile:filePath atomically:YES];

        if (success) {

            NSLog(@"arichiver success");

        }

         

        */

        

        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"ar.text"];

        //读取归档数据

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

        

        //创建解归档对象,对data中的数据进行解归档

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

        

        

        //解归档,还原数据

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

        int scope = [unarchiver decodeIntForKey:@"scope"];

        NSString *name = [unarchiver decodeObjectForKey:@"name"];

        

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

        NSLog(@"scope=%d",scope);

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

        

    

    }

单例设计模式:


//获取单例对象的类方法

+ (AdressBook *)shareInstance {

    

    if (instacne == nil) {

        instacne = [[AdressBook alloc] init];

    }

    

    return instacne;

    

}


//限制方法,限制这个类只能创建一个对象

+ (id)allocWithZone:(NSZone *)zone {

    if (instacne == nil) {

        instacne = [super allocWithZone:zone];

    }

    return instacne;

}


- (id)copyWithZone:(NSZone *)zone {

    return self;

}


- (id)retain {

    return instacne;

}


- (oneway void)release {    

}


- (id)autorelease {

    return self;

}


- (NSUInteger)retainCount {

    return UINT_MAX;

}


沙盒路径:

1Documents目录:您应该将所有de应用程序数据文件写入到这个目录下。这个目录用于存储用户数据或其它应该定期备份的信息。

2AppName.app目录:这是应用程序的程序包目录,包含应用程序的本身。由于应用程序必须经过签名,所以您在运行时不能对这个目录中的内容进行修改,否则可能会使应用程序无法启动。

3Library 目录:这个目录下有两个子目录:Caches Preferences

Preferences 目录:包含应用程序的偏好设置文件。您不应该直接创建偏好设置文件,而是应该使用NSUserDefaults类来取得和设置应用程序的偏好.

Caches 目录:用于存放应用程序专用的支持文件,保存应用程序再次启动过程中需要的信息。

4tmp目录:这个目录用于存放临时文件,保存应用程序再次启动过程中不需要的信息。


获取这些目录路径的方法:

1,获取家目录路径的函数:

NSString *homeDir = NSHomeDirectory();

2,获取Documents目录路径的方法:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *docDir = [paths objectAtIndex:0];

3,获取Caches目录路径的方法:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

NSString *cachesDir = [paths objectAtIndex:0];

4,获取tmp目录路径的方法:

NSString *tmpDir = NSTemporaryDirectory();

5,获取应用程序程序包中资源文件路径的方法:

例如获取程序包中一个图片资源(apple.png)路径的方法:

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];

UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];



做推送:

https://itunes.apple.com/tw/app/apn-tester-free/id626590577?l=zh&mt=12


文件路径处理:

//演示路径

        NSString *path = @"/Users/apple/file.text";

        NSLog(@"演示路径:%@",path);

        

        

        //1.返回路径的组成部分

        NSArray *array = [path pathComponents];

        NSLog(@"pathComponents:%@",array);

        

        //2.路径的最后组成部分

        NSString *lastComponent = [path lastPathComponent];

        NSLog(@"lastComponent:%@",lastComponent);

        

        //3.追加子路径

        NSString *newPath1 = [path stringByAppendingString:@"/appFile.text"];

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

        

        NSString *newPath2 = [path stringByAppendingPathComponent:@"appFile.text"];

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

        

        //4.删除最后的组成部分

        NSString *deleteLast = [path stringByDeletingLastPathComponent];

        NSLog(@"deleteLast:%@",deleteLast);

        

        //5.删除扩展名

        NSString *deleteExtension = [path stringByDeletingPathExtension];

        NSLog(@"deleteExtension:%@",deleteExtension);

        

        //6.获取路径最后部分的扩展名

        NSString *extension = [path pathExtension];

        NSLog(@"extension:%@",extension);

        

        //7.追加扩展名

        NSString *appendExt = [path stringByAppendingPathExtension:@"jpg"];

        NSLog(@"appendExt:%@",appendExt);

        

        

        //NSString ---> NSData

        NSString *s = @"tsdfsdfsdfsdf";

        NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];

        

        

        //NSData -———> NSString

        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

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

        

        //NSMutableData 可变的Data对象,可以追加数据

文件操作:

        NSString *homePath = NSHomeDirectory();

        //源文件路径

        NSString *srcPath = [homePath stringByAppendingPathComponent:@"06 第六课 文件管理.pdf"];

        

        //目标文件路径

        NSString *targetPath = [homePath stringByAppendingPathComponent:@"Documents/06第六课文件管理.pdf"];

        

        

        /*

         注意:使用NSFileHandle只能读写已经存在的文件,不能创建文件

              使用NSFileManager创建文件

         */

        NSFileManager *fileManager = [NSFileManager defaultManager];

        //创建目标文件

        BOOL success = [fileManager createFileAtPath:targetPath contents:nil attributes:nil];

        if (success) {

            NSLog(@"目标文件创建成功!");

        }

        

        //创建用于读取文件的NSFileHandle对象

        NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:srcPath];

        

        //创建用于写入的NSFileHandle对象

        NSFileHandle *wrteHandle = [NSFileHandle fileHandleForWritingAtPath:targetPath];

        

        //从当前偏移量读到文件的末尾,偏移量默认是起始位置

        //NSData *data = [readHandle readDataToEndOfFile];

        NSData *data = [readHandle availableData];

        

        //将数据写入目标文件

        [wrteHandle writeData:data];

        

        //关闭文件

        [readHandle closeFile];

        [wrteHandle closeFile];


        

/*___________________________1.创建文件_____________________________*/

       /*

        //获取当前app的沙盒根目录

        NSString *homePath = NSHomeDirectory();

        

        //追加子路径

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];


        

        NSString *string = @"无限互联";

        //NSString转成NSData对象

        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

        

        //NSFileManager 不能使用alloc创建,这个类设计为单实例

        //NSFileManager *fileM = [[NSFileManager alloc] init];

        

        //NSFileManager 只能通过类方法defaultManager 创建

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

        //根据路径filePath创建对应的文件,注意:只能创建文件,不能创建目录(文件夹)

        BOOL success = [fileManager createFileAtPath:filePath

                                            contents:data

                                          attributes:nil];

        

        

        if (success) {

            NSLog(@"文件创建成功");

        } else {

            NSLog(@"文件创建失败");

        }

        

        

        //创建文件夹

        NSString *filePath2 = [homePath stringByAppendingPathComponent:@"Documents/demo"];

        NSError *error;

        BOOL suucces2 = [fileManager createDirectoryAtPath:filePath2

                               withIntermediateDirectories:YES

                                                attributes:nil

                                                     error:&error];

        if (!suucces2) {

            NSLog(@"创建失败:%@",error);

        }

        */

        

        

/*___________________________2.读取文件_____________________________*/

        

        

        //获取当前app的沙盒根目录

        NSString *homePath = NSHomeDirectory();

        

        //追加子路径

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

        

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

        //根据路径读取文件中的数据

        NSData *data = [fileManager contentsAtPath:filePath];

        

        //NSData NSString

        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"%@",string);

         

        

/*___________________________3.移动(剪切)文件_____________________________*/

        

        /*

        //获取当前app的沙盒根目录

        NSString *homePath = NSHomeDirectory();

        

        //源路径

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];


        //目标路径

        NSString *tagetPath = [homePath stringByAppendingPathComponent:@"Documents/demo/file2.text"];

        

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

         //moveItemAtPath: 移动文件

        BOOL success = [fileManager moveItemAtPath:filePath toPath:tagetPath error:nil];

        if (!success) {

            NSLog(@"移动失败!!");

        }

        */

        

/*___________________________4.复制文件_____________________________*/

        

        /*

        //获取当前app的沙盒根目录

        NSString *homePath = NSHomeDirectory();

        

        //源路径

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/demo/file3.text"];

        

        //目标路径

        NSString *tagetPath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

        

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

         //copyItemAtPath: 将源文件复制到目标路径

        BOOL success = [fileManager copyItemAtPath:filePath toPath:tagetPath error:nil];

        if (!success) {

            NSLog(@"复制失败!!");

        }

         */

        

/*___________________________5.删除文件_____________________________*/

        

        /*

        //获取当前app的沙盒根目录

        NSString *homePath = NSHomeDirectory();

        

        //源路径

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/demo/file3.text"];

        

        

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

        //判断文件是否存在

        BOOL fileExist = [fileManager fileExistsAtPath:filePath];

        

        if (fileExist) {

            

            //removeItemAtPath:删除文件

            BOOL success = [fileManager removeItemAtPath:filePath error:nil];

            if (success) {

                NSLog(@"删除成功!!");

            }

        }

         */

        

/*___________________________6.获取文件的属性_____________________________*/

        /*

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

        NSString *homePath = NSHomeDirectory();

                

        //目标路径

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

        

        //获取到文件的属性信息,文件的属性信息存储fileAttr字典中

        NSDictionary *fileAttr = [fileManager attributesOfItemAtPath:filePath error:nil];

        

        NSLog(@"%@",fileAttr);

        //从字典中通过key:NSFileSize获取到文件大小

        NSNumber *filesize = [fileAttr objectForKey:NSFileSize];

        long sizeValue = [filesize longValue];

        NSLog(@"文件大小:%ld",sizeValue);

        

        

        //如下读取文件的大小,不可取,因为将文件中的数据全都读到内存中,文件大时,太占用内存了

        //NSData *data = [fileManager contentsAtPath:filePath];

        //NSInteger len = data.length;

        

        

        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

         */

字典转模型:

//

//  HMAppInfo.h

//  01-应用程序管理

//

//  Created by apple on 14-8-14.

//  Copyright (c) 2014 itcast. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface HMAppInfo : NSObject


@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *icon;


/**

 @property 

 

 1. 生成getter方法

 2. 生成setter方法

 3. 生成带下划线的成员变量(记录属性内容)

 

 readonly的属性不会生成带下划线的成员变量!

 */

@property (nonatomic, strong, readonly) UIImage *image;


/**

 instancetype 主要用于在类方法实例化对象时,让编译器主动推断对象的实际类型

 

 以避免使用id,会造成开发中不必要的麻烦,减少出错几率!

 

 instancetype是苹果在iOS7才开始主推的

 

 C++11 auto

 swift语言中,绝大多数类的实例化,都不需要再指定类型

 

 instancetype只能用于返回值使用!!!不能当做参数使用

 */


/** 通常在写模型的实例化方法时,以下两个方法,都需要实现 */

/** 使用字典实例化模型 */

- (instancetype)initWithDict:(NSDictionary *)dict;

/** 类方法可以快速实例化一个对象 */

+ (instancetype)appInfoWithDict:(NSDictionary *)dict;


/** 返回所有plist中的数据模型数组 */

+ (NSArray *)appList;


@end






//

//  HMAppInfo.m

//  01-应用程序管理

//

//  Created by apple on 14-8-14.

//  Copyright (c) 2014 itcast. All rights reserved.

//


#import "HMAppInfo.h"


@implementation HMAppInfo

// 合成指令,主动指定属性使用的成员变量名称

@synthesize image = _image;


/**

 使用KVC的注意事项

 

 1> plist中的键值名称必须与模型中的属性一致

 2> 模型中的属性可以不全部出现在plist

 */

- (UIImage *)image

{

    if (_image == nil) {

        _image = [UIImage imageNamed:self.icon];

    }

    return _image;

}


- (instancetype)initWithDict:(NSDictionary *)dict

{

    // self 对象

    self = [super init];

    if (self) {

        // 用字典给属性赋值,所有与plist键值有关的方法,均在此处!

//        self.name = dict[@"name"];

//        self.icon = dict[@"icon"];

        

        // KVC - key value coding键值编码

        // 是一种间接修改/读取对象属性的一种方法

        // KVC 被称为 cocoa的大招!

        // 参数:

        // 1. 数值

        // 2. 属性名称

//        [self setValue:dict[@"name"] forKeyPath:@"name"];

//        [self setValue:dict[@"icon"] forKeyPath:@"icon"];

        // setValuesForKeysWithDictionary本质上就是调用以上两句代码

        [self setValuesForKeysWithDictionary:dict];

    }

    return self;

}


+ (instancetype)appInfoWithDict:(NSDictionary *)dict

{

    // self class

    return [[self alloc] initWithDict:dict];

}


+ (NSArray *)appList

{

    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil]];

    

    // 创建一个临时数组

    NSMutableArray *arrayM = [NSMutableArray array];

    

    // 遍历数组,依次转换模型

    for (NSDictionary *dict in array) {

        [arrayM addObject:[HMAppInfo appInfoWithDict:dict]];

    }

    

    return arrayM;

}


@end


使用:

- (NSArray *)appList

{

    if (_appList == nil) {

        _appList = [HMAppInfo appList];

    }

    return _appList;

}




创建蒙板(遮罩)

  1.创建蒙板(遮罩)

   UIButton *cover=[[UIButton alloc]initWithFrame:self.view.bounds];

    cover.backgroundColor=[UIColor colorWithWhite:0.0 alpha:0.5];

    [self.view addSubview:cover];

    _cover.alpha=0.0;

    [_cover addTarget:self action:@selector(smallImage:) forControlEvents:UIControlEventTouchUpInside];

    //2.将图像按钮弄到最前面来

    [self cover];

    [self.view bringSubviewToFront:self.CentImage];

    //3.动画将按钮放大

    CGFloat w=self.view.bounds.size.width;

    CGFloat h=w;

    CGFloat y=(self.view.bounds.size.height-w)*0.5;

    [UIView animateWithDuration:1 animations:^{

        self.CentImage.frame=CGRectMake(0, y, w, h);

        _cover.alpha=1;

    } completion:^(BOOL finished) {

        

    }];



UITableView的一些使用方法:


_tableView.dataSource = self;

_tableView.delegate = self;

_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

/**

 UITableViewStylePlain,     // 平板的格式

 UITableViewStyleGrouped    // 分组的格式

 */

// 设置行高

    self.tableView.rowHeight = 120;

    // 分隔线

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

    // headView,放在tableView最顶部的视图,通常用来放图片轮播器

    UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 130)];

    head.backgroundColor = [UIColor blueColor];

    self.tableView.tableHeaderView = head;

    

    // footerView,通常做上拉刷新

    UIView *foot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

    foot.backgroundColor = [UIColor redColor];

    self.tableView.tableFooterView = foot;


右侧索引

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

{

    // 索引数组中的"内容",跟分组无关

    // 索引数组中的下标,对应的是分组的下标

//    return @[@"哇哈哈", @"hello", @"哇哈哈", @"hello", @"哇哈哈", @"hello", @"哇哈哈", @"hello"];

    

    // 返回self.carGrouptitle的数组

//    NSMutableArray *arrayM = [NSMutableArray array];

//    for (HMCarGroup *group in self.carGroups) {

//        [arrayM addObject:group.title];

//    }

//    return arrayM;

    

    // KVCcocoa的大招

    // 用来间接获取或者修改对象属性的方式

    // 使用KVC在获取数值时,如果指定对象不包含keyPath"键名",会自动进入对象的内部查找

    // 如果取值的对象是一个数组,同样返回一个数组

    NSArray *array = [self.carGroups valueForKeyPath:@"cars.name"];

    NSLog(@"%@", array);

    

    return [self.carGroups valueForKeyPath:@"title"];

}


    // 开始编辑,一旦editing == YES就默认开启删除模式

    self.tableView.editing = YES;

// 只要实现了此方法,就能够支持手势拖拽删除了,删除需要自己干!

/**

 UITableViewCellEditingStyleNone,

 UITableViewCellEditingStyleDelete,     删除

 UITableViewCellEditingStyleInsert      添加

 */

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        NSLog(@"要删除");

        

        // MVC => 数据是保存在模型中

        // 1. 删除self.dataListindexPath对应的数据

        [self.dataList removeObjectAtIndex:indexPath.row];

        NSLog(@"%@", self.dataList);

        

        // 2. 刷新表格(重新加载数据)

        // 重新加载所有数据

//        [self.tableView reloadData];

        // deleteRowsAtIndexPaths让表格控件动画删除指定的行

        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];

    } else if (editingStyle == UITableViewCellEditingStyleInsert) {

        NSLog(@"要添加数据");

        

        // 1. 向数组添加数据

        [self.dataList insertObject:@"王小二" atIndex:indexPath.row + 1];

        // 2. 刷新表格

//        [self.tableView reloadData];

        // insertRowsAtIndexPaths让表格控件动画在指定indexPath添加指定行

        // 新建一个indexPath

        NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];

 

        [self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationMiddle];

    }

}


// 只要实现此方法,就可以显示拖动控件

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath

{

    // 界面数据UITableView已经完成了

    // 调整数据即可

//    [self.dataList exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];

    // 1. 将源从数组中取出

    id source = self.dataList[sourceIndexPath.row];

    // 2. 将源从数组中删除

    [self.dataList removeObjectAtIndex:sourceIndexPath.row];

    NSLog(@"%@", self.dataList);

    

    // 3. 将源插入到数组中的目标位置

    [self.dataList insertObject:source atIndex:destinationIndexPath.row];

    

    NSLog(@"%@", self.dataList);

}


#pragma mark - 代理方法

// 返回编辑样式,如果没有实现此方法,默认都是删除

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{f

//    if (indexPath.row % 2) {

//        return UITableViewCellEditingStyleInsert;

//    } else {

//        return UITableViewCellEditingStyleDelete;

//    }

    return UITableViewCellEditingStyleInsert;

}

注意使用模型来给cell中属性赋值

自定义代理

HMAppView.h文件

@class HMAppInfo, HMAppView;


// 1. 协议名以类名开始+Delegate

@protocol HMAppViewDelegate <NSObject>


@optional

// 2. 协议方法,以类名开始(没有类前缀),第一个参数是自己

// 只是定义方法名,不做具体实现

- (void)appViewDidClickDownloadButton:(HMAppView *)appView;


@end

@interface HMAppView : UIView


// 3. 定义代理属性,遵守了HMAppViewDelegate协议的任意一个对象,都可以成为代理

@property (nonatomic, weak) id<HMAppViewDelegate> delegate;


/** 类方法,方便调用视图 */

+ (instancetype)appView;

/** 实例化视图,并使用appInfo设置视图的显示 */

+ (instancetype)appViewWithAppInfo:(HMAppInfo *)appInfo;


// 自定义视图中显示的数据来源是数据模型

// 使用模型设置自定义视图的显示

@property (nonatomic, strong) HMAppInfo *appInfo;


@end


uiToolBar

    UIToolbar * tbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 44, 320, 44)];

    //创建UIToolbar对象

    tbar.tintColor = [UIColor greenColor];

#if 1

    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    

    NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:0];

    for (int i = 0; i < 3; i++) {

        UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil];

        [array addObject:item];

        [array addObject:spaceItem];

    }

    UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0, 0, 50, 30);

    [btn setTitle:@"xx" forState:UIControlStateNormal];

    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:btn];

    

    //要用initWithCustonView:

    [array addObject:item];

    

    tbar.items = array;

#else

    //UIToolbar中加入的按钮都是UIBarButtonItem类型

    UIBarButtonItem * item0 = [[UIBarButtonItem alloc] initWithTitle:@"上一页" style:UIBarButtonItemStyleDone target:self action:nil];

    UIBarButtonItem * item1 = [[UIBarButtonItem alloc] initWithTitle:@"首页" style:UIBarButtonItemStyleDone target:self action:nil];

    UIBarButtonItem * item2 = [[UIBarButtonItem alloc] initWithTitle:@"下一页" style:UIBarButtonItemStyleDone target:self action:nil];

    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    //spaceItem是一个弹簧按钮(UIBarButtonSystemItemFlexibleSpace)

    tbar.items = [NSArray arrayWithObjects:item0, spaceItem, item1, spaceItem, item2, nil];

    #endif

    //要达到相同的效果,也可以插入一个buttonbutton的类型为Customenabled设置为NO

    [self.view addSubview: tbar];


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
// // main.m // Hello World_Code // #import #import "AppDelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } // // AppDelegate.h // Hello World_Code // #import @interface AppDelegate : UIResponder @property (strong, nonatomic) UIWindow *window; @end // // AppDelegate.m // Hello World_Code // #import "AppDelegate.h" @implementation AppDelegate - (void)dealloc { [_window release]; [super dealloc]; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(320/2.0 - 140/2.0, 80, 140, 40)]; // 1 label.text = @"Hello World"; label.backgroundColor = [UIColor cyanColor]; label.textAlignment = NSTextAlignmentCenter; [self.window addSubview:label]; // 2 [label release]; // 1 return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值