block代码块 和property协议
1.block类型是一个c级别的语法和运行机制,他与标准c函数类似,不同之处在于,它除了有可执行代码以外,还包含了与堆。栈内存绑定的变量,因此block 对象包含着一组状态数据,这些数据在程序执行是用于对行为产生影响,block被设计为可同时兼容三种语言 oc 、c++ 、c。
block 的基本使用
int(^myBlock )(int)=(int num){ return }
1) 无参无返回值
定义一个没有参数\没有返回值的block变量,同时赋值。
void (^block变量名)()=^(){
代码块的语句
}
void (^myBlock1)(int)=^( ){
NSLog(@"xxxx");
}
//使用block变量
myBlock1(); //这样就打印xxxxx 没参数^小括号可以省略
2)有参数无返回值
void(^变量名)(参数类型及个数)=^(形参列表){
代码块语句
}
viod (^myBlock2)(int,int)=^(int a, int b){
NSLog(@"a+b=%d",a+b);
}
myBlock2(3,6);
//先定义变量,再赋值
myblock2=^(int x,inty){
NSLog(@"x*y =%d",x*y);
}
3)有参数有返回值
定义一个有从哪回溯有返回值的block
int(^myBlock3)(int,int)=^(intx,inty){
return x+y;
}
//使用block ,接受返回值
int sum =myBlock3 (23,45 );
//重新给变量赋值
myblock3=^(int x,inty){
return x*y;
}
2.block的typedef
利用typedef定义的block类型(和指向函数的只注重很像)
typedef void(^myBlock)() :
格式 : typedef 返回值类型(^新别名)(参数类型列表)
typedf int (^myBlock1)(int ,int);
给没有返回值,没有参数的block起一个别名
myblock是一个类型不在是一个单纯的变量
typedef void (^myblock)();
myblock f1;
//block类型的变量
f1 =^{
NSLog(@“hellowworld");
}
//使用
f1();
定义有参数 \有返回值的block类型
int (^block1)(int,int)=^(inta,intb){
return a=b;
}
定义了一个block1的类型 返回值是int 有两个int类型参数
typedef int(^block1)(int,int);
block1 b1;
b1 =^(int x,int y){
return x-y;
}
int s= b1(2,3);
连续定义多个 block1类型的变量
block1 n,n2,n2;
3.block访问外部变量
1)在block内部可以访问外部的变量
当定义block的时候会把外部变量以const 的方式复制一份,存放到block的所在内存中
2)block内部不可以修改外部的变量值
3)__block 修饰的变量内部可以修改 应为这里不再以const的方式拷贝
4.注意:
1)静态变量和全局变量。在不加 __block 都会直接引用变量地址,也就意味着可以修改变量的值,在没有__block参数的情况下
2)全局变量block:定义在函数外部的block是global 另外如果函数内部的block,但是没有捕捉任何自动变量,那么他也是全局的
3)栈block 区别,是否引用了外部变量
4)堆block 则是对栈block copy得来,对全局block copy不会有任何作用,返回的依然是全局block。
5.block作为函数的返回值
步骤 1.使用typedef定义一个新类型
//给block起个别名
typedef int (^newType)(int num1,int num2);
2.使用新类型作为函数的返回值
//定义一个返回值是block类型的函数
newType test4(){}
3.定义变量接受函数的返回值(block类型)
4.调用block
//block类型作为函数的返回值
newType test(){
newType w1 =^{
NSLog(@"xxxx");
NSLog(@"helloword");
}
return w1;//返回值
}
//定义block类型的变量接受函数返回的结果
newType n1 =test();
//执行block
n1();
//重新定义一个新的类型newType2
typedef int (^newType2)(int,int);
newType2 test2 {
return^(int a,int b){
return a+b;
}
}
//n2 = ^(int a,int b){ return a+b ; };
newType2 n2 = test2();
//调用block
int s = (23,23);
7.block的掌握技巧
1)block 结构的快速提示: 输入inlineBlock
2)我们在定义block变量的时候,形参类型及个数 这个位置处可以加上形参名
test(^int(int,int)){}
实现程序员工作
#import<Foundation/Foundation.h>
//block类型的变量 workBlock 作为函数的参数
void work(void(^workBlock)() ){
NSLog(@"起床刷牙");
NSLog(@"去车站");
NSLog(@"坐车");
workBlock();//打印其它的
NSLog(@"去车站");
NSLog(@"坐车回家");
NSLog(@"吃饭");
NSLog(@"睡觉");
}
void workday(intn){
typedef void(^workBlock) ();
workBlock w;
switch (n) {
case 1:
w=(^{
NSLog(@"了解项目");
});
break;
case 2:
w=(^{
NSLog(@"了解项目");
});
break;
case 3:
w=(^{
NSLog(@"了解项目");
});
break;
case 4:
w=(^{
NSLog(@"了解项目");
});
break;
case 5:
w=(^{
NSLog(@"离职");
});
break;
default:
break;
}
//调用函数
work(w);
}
int main(intargc, const char * argv[]) {
@autoreleasepool {
workday(5);
return 0;
}
}
二、protocol(协议)
1.protocol 概念及基本使用
什么是协议:一些方法的声明 ,一般写到一个.h头文件中
方法有两种:必须实现的 和选择实现的
协议的作用: 供其他的类区遵守
如果一个类遵守了一个协议,就应该实现这个协议宏定义的必须要实现的方法。
2. 如何定义一个协议
@protocol xxx <NSObject> 默认的情况下遵守的 NSObject 协议
@end
类遵守协议的格式
1)遵守协议
先导如入头文件
@interface Person :NSObject <xxx>;
@end
2)遵守多个协议
@interface 类名:NSObject<xxx,aaa ,bbb>;
@end
#import <Foundation/Foundation.h>
//定义一个协议
//定义协议的流程-->定义协议-->让类遵守这个协议-->实现协议中对应的方法(必须要实现的)
@protocol basepProtocol <NSObject>
//声明一些方法
-(void)eat;
-(void)run;
@end
//Person 遵守这个协议
@intrface Person :NSObjeect<baseProtocol>
@end
@implementation Person
-(void)eat{
NSLog(@"人在吃法饭");
}
-(void)run{
NSLog(@"人在跑步");
}
@end
当我们遵守了某个协议后,就有相当于这个类有了协议中所有的方法声明
3.protocol的其他用法
protocol的使用注意
1)protocol :就一个用途,用来声明一大堆的方法(不能声明成员变量),不能写实现
2)只要某个类遵守了这个协议,就拥有了这个协议中的所有方法
3)只要父类遵守了某个协议,那么子类也遵守 ,实现了协议方法,这些方法可以被子类继承
4)protocol声明的方法可以让任何类区实现 ,protocol就是协议
5)oc中不能继承多个类(单继承)但是能够遵守多个协议。继承( :)协议( <> )
6)基协议:<NSObject>是基协议,是最根本的协议,其中声明了很多方法。
7)协议可以遵守协议,一个协议遵守了另一个协议,就可以拥有另一个协议中的方法声明
4.protocol 中的@reuired 和@optional
@required和@optional 是协议方法声明中的两个关键字
他们主要控制方法是否要实现(默认的是@required),
用途 在于程序员之间的交流
@requried 表示必须要实现的方法
@optional 可以选择实现方法
5.protocol 类型限制
需要一女朋友的条件 定个协议
housHoldProtocl.h
@protocol houseHoldProtocol <NSObject>
- (void)zuoFan;
- (void)xiyifu;
@optional
-(void)job;
@end
1)使用id存储对象,对象的类型限制
格式 id<协议名称> 变量名
id <Myportocol> obj1;
//这样写后,表示是给人都满足条件
所以改为id<houseHoldProtocol>girl ;
这样就行限制了 传进来的对象要遵守了协议才可以赋值
2)对象赋值类型限制
格式:类名<协议名>*变量名
Person<hoseHoldProtocol>*p
这样必须是人的类的对象才能赋值
3)对象的关联关系
要求人的狗会算数
@intterface Person:NSObject
//限制了这里传入的狗必须是遵守了dogProtocol的狗
@property(nonatomic,strong)Dog<dogProtocol>*dog;
@end
//狗遵守协议
@intreface Dog:NSObject<dogProtocol>
@end
id 和instancetype的区别
1)instancetyp只能作为函数或方法的返回值
2)id能作为方法或者函数的返回值、参数类型,也能用来定义一个变量
3)instancetype 对比id的好处: 能精确的的限制返回值的具体类型
6.protocol代理模式设计
实现 婴儿饿了要吃东西 ,困了要睡觉,
婴儿类 保姆类
#import <Foundation/Foundation.h>
@protocolbaoMuProtocol <NSObject>
-(void)eatToBaby;
-(void)sleepToBaby;
@end
import<Foundation/Foundation.h>
#import"baoMuProtocol.h"
@class baby;
@interface baoMu: NSObject<baoMuProtocol>
@property(nonatomic,weak) baby *baby;
@end
#import"baoMu.h"
#import"baby.h"
@implementationbaoMu
-(void)eatToBaby{
NSLog(@"保姆正在给baby喂奶");
}
-(void)sleepToBaby{
NSLog(@"保姆正在哄baby睡觉");
}
@end
#import<Foundation/Foundation.h>
@class baoMu;
#import"baoMuProtocol.h"
@interface baby: NSObject
@property(nonatomic,strong) baoMu<baoMuProtocol>*baomu;
-(void)babyWantEat;
-(void)babyWantsleep;
@end
#import"baby.h"
#import"baoMu.h"
@implementationbaby
-(void)babyWantEat{
NSLog(@"baby在哭。。。。");
[self.baomu eatToBaby];
}
-(void)babyWantsleep{
NSLog(@"baby在哭。。。。");
[self.baomu sleepToBaby];
}
@end
#import<Foundation/Foundation.h>
#import"baby.h"
#import"baoMu.h"
int main(intargc, const char * argv[]) {
@autoreleasepool {
baoMu *baomu =[[baoMu alloc] init];
baby * ba =[[baby alloc] init];
ba.baomu = baomu;
[ba babyWantEat];
}
return 0;
}
protocol代理设计模式概念
传入对象,代替当前类完成某个功能,称为代理模式。
利用协议实现代理模式的主要思路:
1)定义一个协议,里面声明代理需需要实现的方法列表。
2)创建一个代理类,遵守上面的代理协议
3)在需要代理的类中,定义一个对象类型为id且遵守代理协议的成员变量
4)在类中调用成员变量_delegate(代理的方法),调用代理的类方法
5)main.m或其他类文件中,为类的成员变量赋值
理解应用饿哦那个过中介找房子
#import<Foundation/Foundation.h>
@protocolfindHouseProtocol <NSObject>
-(void)findHouse;
@end
#import<Foundation/Foundation.h>
#import"findHouseProtocol.h"
@interfaceLinkHome : NSObject<findHouseProtocol>
@end
#import"LinkHome.h"
#import"findHouseProtocol.h"
@implementationLinkHome
-(void)findHouse{
NSLog(@"链家地产正在给学生找房子");
}
@end
#import<Foundation/Foundation.h>
#import"findHouseProtocol.h"
@interfaceStudent : NSObject
@property(nonatomic ,strong) id<findHouseProtocol>delegate;
-(void)needHouse;
@end
#import"Student.h"
#import"LinkHome.h"
@implementationStudent
-(void)needHouse{
NSLog(@"学生需要一个温暖的家");
[self.delegate findHouse];
}
@end
#import<Foundation/Foundation.h>
#import"Student.h"
#import"LinkHome.h"
int main(intargc, const char * argv[]) {
@autoreleasepool {
//代理类
LinkHome *li = [[LinkHome alloc] init];
Student*stu =[[Student alloc] init];
stu.delegate=li;
[stu needHouse];
//代理类 LinKhome
//代理对象 delegate
//协议内容findHouseProtocol
//协议内容 findHouse
}
return 0;
}
Foundation 框架
一.Foundation框架的介绍
框架是由许多类、方法、函数、文档按照一定的逻辑组织起来的集合,以便使研发程序变得更容易在os x下的mac操作系统中大约有80个框架为所有程序开发奠定基础的框架称为Foundation框架
Cocoa 是Foundation和AppKit
Cocao Touch是Foundation和UIKit
要想使用Foundation框架中的功能,包含它的主文件即可#import<Foundation/Foundation.h>
Foundation 框架包含了很多开发中常用的数据类型结构体、枚举、类等。
二、NSString介绍及基本使用
一个NSString对象就代表一个字符串(文字类容),一般称为NSString为字符串类
NSString的创建方式
1)最直接的方式(这是常量字符串)
NSString *str = @"abc";
2)格式化的方式
NSString *str1 =[NSString stringWithFormat:@"%@",@"jack"];
NSString *str2 =[NSString stringWithFormat:@"my age is %d",10]
注意:这中写法,字符串是存储在内存的堆区(地址不一样)
3)从文件中读取
NSString *str3 = [NSStringWithContentsOfFile:@"/Users/apple/Desktop/t.txt"encoding:NSUTF8StringEncodingerror:&err];
注意:
如果读取到内容
if(err == nil){
NSLog(@"读取成功的情况");
NSLog(@"%@",str3);
}else{
NSLog(@"文件读取失败");
NSLog(@"%@",err);
}
//可以通过[err loclizedDescription];打印简单的错误信息
//NSLog(@"%@",[err localizeDescription])
三、.NSURL读写字符串
NSString *str = @"$10000000";
//URL统一资源定位符
//NSURL OC提供了一个URL处理的一个类
//http https// 加密 ftp:// file:// 本地文件 NSURL 写入文件
1)通过URLWithString 构建一个NSURL
URLWithString 可以构建本地路径的URL
可以构建路径,调用手机系统的程序
NSURL *url = [NSURL URLWithString:@"sms://10086"];
NSURL *url = [NSURL URLWithString:@"file:///Users/apple/Desktop/3.txt"];
2) fileURLWithPath 获取本地文件路径
NSURL *url = [NSURLfileURLWithPath:@"/Users/zhaoxiaohu/Desktop/4.txt"];
if([str writeToURL:url atomically:YES encoding:NSUTF8StringEncodingerror:nil]){
NSLog(@"写入成功");
}
NSString *str2 = [NSString stringWithContentsOfURL:urlencoding:NSUTF8StringEncoding error:nil];
四.NSString 的使用介绍
1.字符串比较
NSString *str1 =@"_abc";
NSString *str2 =@"bcd";
//取出每个字符的ASCII 码值,比较ASSICC码值的大小
//compare方法比较大小 默认的区分大小写 这个函数不能增加条件
// NSComparisonResultreslut = [str1 compare:st2];
//比较的时候,不区分大小写,参考字符的个数
NSComparisonResult result =[str1 compare:str2options:NSCaseInsensitiveSearch | NSNumericSearch];
switch (result) {
case NSOrderedAscending:
NSLog(@"str>str2 升序");
break;
case NSOrderedDescending:
NSLog(@"str<str2 降序");
break;
case NSOrderedSame:
NSLog(@"str==str2 ");
break;
default:
break;
}
//地址比较判断字符处是否相等。真正的相等 他是区分大小写的
if ( [str1 isEqualToString:str2]){
NSLog(@"相等");
}else{
NSLog(@"不相等");
}
2.NSString前后缀检查及搜索
//检车字符串的前后缀
NSString *url=@"http://ios.itcat.cn";
1)如何检测一个字符串是否是网址 http:// https://
//检测一个字符串的前后缀是否以 http:// https:// 开头
//[str hasPerfix:@"要检测的内容"]
if( [url hasPrefix:@"http://"]| [urlhasPrefix:@"https://"]){
NSLog(@"是一个网址");
}else{
NSLog(@"这不是一个网址");
}
2)检测车字符串的后缀
//xxx.jpg 判断后缀是不是."jpg"
NSString *imgName =@"xxxx.jpg";
if ([imgName hasSuffix:@".jpg"]|[imgNamehasSuffix:@".png"]|[imgName hasSuffix:@".jpeg"])
{
NSLog(@"这是一个图片");
}else{
NSLog(@"这不是一个图片");
}
3.字符串的查找
查找某个字符串在另外一个字符串首次出现的位置
查找2 在 1中首次出现的位置
如果查找到了,返回2在1中的位置和长度
如果查找不到,返回的信息:
location 特别大的数(NSNotFound)最大的long类型的数
length 0
range 结构体变量 NSRange 结构别名
NSString *str =@"ssadjdiosdknkliiwprp";
NSString *str1=@"ios";
NSRange range =[str rangeOfString:str1];
//range.location 表示字符串首次出现的位置
//range.length 字符串出现的长度(实质上就是子字符串的长度)
if (range.location!=NSNotFound) {
NSLog(@"%lu,%lu",range.location,range.length);
}else{
NSLog(@"在%@中没有找到这个字符串%@",str,str1);
}
4.字符串的截取和替换
NSString *str=@"http://www.baidu.com";
1).从开始位置,到最后结束(包含xx这个位置)
NSString *str1 =[str substringFromIndex:5];
NSLog(@"str1 =%@",str1);
2)从开始位置到xx位置结束(不包含文件的位置)
NSString *str2 = [str substringToIndex:5];
NSLog(@"str2 =%@",str2);
3)截取一范围 range
NSRange r1={3,4};
NSString *str3=[str substringWithRange:r1];
NSLog(@"str3 =%@",str3);
4)字符串的替换
//@"sadsaldjejeiwrwwrjasjlasd"------>a 替换成"*"
//@"sad dfd f gfgf fhf sd"--->去掉空格
NSString *str = @"sadsaldjejeiwrwwrjasjlasd";
//str stringByReplacingOccurrencesOfString:@"源字符串中的内容"withString:@"要替换成新的内容"把a替换成 *
NSString *newStr =[strstringByReplacingOccurrencesOfString:@"a" withString:@"*"];
NSLog(@"newStr= %@",newStr);
//把空格给去掉
str=@"sad dfd f gfgf fhf sd";
newStr =[str stringByReplacingOccurrencesOfString:@"a"withString:@""];
NSLog(@"newStr= %@",newStr);
5.NSRange的使用
NSRange range; //结构体变量
NSRange * r; // r结构体指针
//range变量的初始化方式
1)通过结构体变量访问成员
range.location =3;
range.length =2;
2)结构体变量整体赋值n
range =(NSRange){5,3};
NSRange r2={5,6};//最简单
//oc中新增的 NSMakeRange结构体变量赋值
NSRange r4 =NSMakeRange(3, 4);
//把结构体变量转换为 NSString类型
NSLog(@"%@",NSStringFromRange(r4));
6.NSString的其他区用法
OC的字符串和 C的字符串互相转换问题
char* NSString
1) C---->OC对象
char *s = "zhangsanfeng";
printf("%s\n",s);
思路:创建一个OC的字符串对象,用C语言的字符串创建
NSString *str = [NSString stringWithUTF8String:s];
NSLog(@"str = %@",str);
2) OC对象 --> C的字符串
NSString *str2 = @"zbz";
// 把str2 转 C的字符串
const char *s1 = [str2 UTF8String];
printf("s1 = %s\n",s1);
五、NSMutableString的使用介绍
1.使用介绍
//不可变: 字符串占用的空间 和 字符串 的内容,都不能改变
//可变: 字符串占用的空间和字符串的内容,都可以改变
NSString *str = @"Jack"; //常量区
NSLog(@"str addr =%p",str);
str = @"Rose";
NSLog(@"str addr =%p",str);
//可变的字符串
NSMutableString *str2 = [NSMutableStringstringWithFormat:@"Jack"];
NSLog(@"str2 addr =%p",str2);
[str2 appendString:@"&Rose"];
NSLog(@"str2 addr =%p",str2);
NSLog(@"str2 = %@",str2);
//思考:
//创建一个可变的空字符
NSMutableString *str3 = [NSMutableString string];
NSLog(@"str3 = %@",str3);
for (int i=0; i<10; i++) {
[str3 appendString:@" itcast"];
}
NSLog(@"str3 = %@",str3);
2.常用方法
NSMutableString *str = [NSMutableString string];
1) appendFormat 格式化的添加字符串
// 0123456789
[str appendFormat:@"http://www.baidu.com/%d",100];
//str http://www.baidu.com/100
NSLog(@"%@",str);
2) 删除字符串一部分内容
[str deleteCharactersInRange:NSMakeRange(3, 4)];
NSLog(@"%@",str);
3) 插入一个字符串
[str insertString:@"p://" atIndex:3];
NSLog(@"%@",str);
4) 替换字符串的一部分内容
[str replaceCharactersInRange:NSMakeRange(11, 5)withString:@"itcast"];
NSLog(@"%@",str);
}
六、NSArray使用介绍
1.介绍
NSArray特点: 一旦创建成功,内容不可改变 只能存放OC对象
1)创建一个空数组
NSArray *arr1 = [NSArray array];
2)创建数组,只有一个元素
NSArray *arr2 = [NSArray arrayWithObject:@"1"];
3)创建数组,有多个元素
nil 表示数组赋值结束
// 常见写法
NSArray *arr3 = [NSArrayarrayWithObjects:@"one",@"two",@1, nil];
NSLog(@"arr3 = %@",arr3);
4)调用对象方法,创建数组
//nil Nil NULL NSNULL
NSArray *arr4 = [[NSArray alloc]initWithObjects:@"three",[NSNull null],@"four", nil];
NSLog(@"arr4 = %@",arr4);
5)用一个数组可以创建另外一个数组
NSArray *arr5 = [NSArray arrayWithArray:arr3];
NSLog(@"arr5 = %@",arr5);
2.数组的常见用法
NSArray *arr3 = [NSArrayarrayWithObjects:@"one",@"two",@1,@"three", nil];
NSLog(@"arr3 = %@",arr3);
1)获取数组的长度 count获取数组的元素的个数
NSLog(@"%ld",arr3.count);
2)根据下标,获取下标对应的对象
NSLog(@"%@",[arr3 objectAtIndex:3]);
3)返回元素的下标
NSUInteger loc = [arr3 indexOfObject:@"three"];
NSLog(@"%ld",loc);
4)数组中是否包含了某个元素
if([arr3 containsObject:@"four"]){
NSLog(@"包含此元素");
}else{
NSLog(@"不包含");
}
用简化的方式,来定义和访问数组元素
1)用简化的方式,定义数组
格式: @[ 数组元素 ]
NSArray *arr =@[@"1",@"one",@"3",@4,@"ONE"];
NSLog(@"arr = %@",arr);
NSString *str =[arr objectAtIndex:2];
NSLog(@"%@",str);
2)用简化的方式访问数组元素
str = arr[1]; //C语言形式的数组元素访问
NSLog(@"%@",str);
3.遍历方法
定义一个数组
NSArray *arr =@[@"one",@"two",@"three",@"four"];
对数组进行遍历
1) 普通的方式,通过下标访问
for (int i=0; i<arr.count; i++) {
NSLog(@"-> %@",arr[i]);
}
2) 快速枚举法 for循环的增强形式
for (NSString * str in arr) {
NSLog(@"---> %@",str);
}
3) 使用block的方式,进行访问
数组元素 元素下标 是否停止
//stop:YES 会停止, stop:NO 不会停止
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if(idx == 2){
*stop = YES; //停止 // break;
}else{
NSLog(@"idx = %ld,obj = %@",idx,obj);
}
}];
4.读写文件
NSArray *array = [NSArrayarrayWithObjects:@"one",@"zbz",@"cgx",@"sb",@"cjk",@"senni",nil];
//把NSArray 中的内容,写入到文件中
//arr.plist 一种特殊的文件格式
BOOL isWrite = [arraywriteToFile:@"/Users/zhaoxiaohu/Desktop/arr.xml" atomically:YES];
if(isWrite){
NSLog(@"写入成功");
}
从文件中,读取一个数组信息
NSArray *readArr = [NSArrayarrayWithContentsOfFile:@"/Users/zhaoxiaohu/Desktop/arr.xml"];
NSLog(@"readArr = %@",readArr);
5.NSArray 与数组
//定义一个数组
NSArray *arr = @[@1,@2,@3,@4];
1)需求: 把数组中的元素用 "-" 连接起来
[数组componentsJoinedByString @"分隔符"];
// 1-2-3-4
NSString *str = [arr componentsJoinedByString:@"-"];
NSLog(@"str = %@",str);
2) 给一个字符串,分割成一个数组
// 400-800-12580 //取得 400 12580 800
NSString *str2 = @"400-800-12580";
NSArray *arr2 = [str2 componentsSeparatedByString:@"-"];
NSLog(@"%@",[arr2 firstObject]);
NSLog(@"%@",[arr2 lastObject]);
NSLog(@"%@",arr2[1]);
str2 = @"400-800-12580#400-888-11200";
NSArray *arr3 = [str2 componentsSeparatedByString:@"#"];
NSLog(@"arr3 = %@",arr3);
//第一个电话的每一部分
NSArray *arr4 = [[arr3firstObject] componentsSeparatedByString:@"-"];
NSLog(@"arr4 = %@",arr4);
NSArray *arr5 = [[arr3 lastObject]componentsSeparatedByString:@"-"];
NSLog(@"arr5 = %@",arr5);
}
七、NSMutableArray的基本使用
数组的使用
1)创建数组
i. 空数组
NSMutableArray *arr1 = [NSMutableArray array];
NSLog(@"%p",arr1);
ii.创建的时候初始化一个元素
NSMutableArray *arr2 =[NSMutableArray arrayWithObject:@"one"];
iii.创建数组的时候,初始化多个元素
NSMutableArray *arr3 = [NSMutableArrayarrayWithObjects:@"one",@"two",@3,nil];
IV . 创建一个数组,并且指定长度,
NSMutableArray *arr4 = [NSMutableArray arrayWithCapacity:5];
2) 添加元素
[arr1 addObject:@"fengjie"];
NSLog(@"%p",arr1);
//插入元素到指定的位置
[arr1 insertObject:@"zbz" atIndex:0];
3) 删除元素
根据对象内容删除
// [arr1removeObject:@"zbz"];
//根据位置删除
// [arr1removeObjectAtIndex:1];
//全部删除
[arr1 removeAllObjects];
4) 修改元素
//two --> four
[arr3 replaceObjectAtIndex:1 withObject:@"four"];
//four --> five
//更加简单地方法
arr3[1] = @"five";
NSLog(@"%@",arr3);
5) 查找元素
BOOL isSearch = [arr3 containsObject:@"four"];
NSLog(@"%d",isSearch);
/6) 交换元素
// 1 2 3 4 5
// 5 2 3 4 1
//temp = a[0];
//a[0] = a[len-1];
//a[len-1] = temp;
NSMutableArray *arr5 =[NSMutableArray arrayWithObjects:@1,@2,@3,@4,@5,nil];
// 可以交换数组元素
[arr5 exchangeObjectAtIndex:0 withObjectAtIndex:4];
NSLog(@"%@",arr5);
八、NSDictionary的介绍及使用
1.介绍
NSDictionary 不可变的,一旦创建,内容就不能添加\删除(不能改动)
1)创建空字典
NSDictionary *dict1 = [NSDictionary dictionary];
// key value
// zs ---> 张三
// ls ---> 李四
// mz ---> 码子
2)创建只有一组键值对的字典
NSDictionary *dict2 = [NSDictionarydictionaryWithObject:@"zhangsan" forKey:@"zs"];
3)创建多组键值对的字典
// value值,key值
NSDictionary *dict3 = [NSDictionarydictionaryWithObjectsAndKeys:@"value1",@"k1",@"value2",@"k2",nil];
//注意;
// 字典的key值和value值,都必须是对象
4)快速创建一个字典
@{,,key值:value值,,,};
key值不能重复:
如果重复了,也不会报错
如果重复了,最后添加的将不能够保存到字典中
NSDictionary *dict4 =@{@"zs":@"zhaosi",@"zs":@"zhangsan",@"ls":@"lisi",@"bz":@"banzhang"};
NSLog(@"%@",dict4); //以%@格式打印字典,控制台输出一个{ }
5)获取字典的长度
NSLog(@"%lu",dict4.count);
6)根据key值取出value值
// zs zhaosi
// key
NSString *str = [dict4 objectForKey:@"zs"];
NSLog(@"str = %@",str);
7)字典的遍历问题
/第一步:获取所有的key
第二步:根据key获取value
for(NSString *key in dict4){
NSLog(@"key = %@,value = %@",key,[dict4 objectForKey:key]);
}
key value stop
[dict4 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@ --> %@",key,obj);
}];
2.简写及文件操作
1)用简写形式定义一个字典
NSDictionary *dict =@{@"zbz":@"zhangbozhi",@"cgx":@"chenguanxi",@"xzmly":@"hello"};
2)用简写形式,获取key对应的value
NSLog(@"%@",dict[@"zbz"]);
3)把字典保存到文件中
BOOL isWrite = [dictwriteToFile:@"/Users/zhaoxiaohu/Desktop/dict.plist" atomically:YES];
if (isWrite) {
NSLog(@"写入成功");
}
4)从文件中读取字典
NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/zhaoxiaohu/Desktop/dict.plist"];
NSLog(@"readDict = %@",readDict);
九、NSMutableDictionary的介绍及使用
1)可变字典的创建
NSMutableDictionary *dict1 = [NSMutableDictionary dictionary]; //创建空字典
NSMutableDictionary *dict2 = [NSMutableDictionarydictionaryWithCapacity:3];
2)给可变字典添加键值对
[dict1 setValue:@"zhaosi" forKey:@"ls"];//因为key值重复了,所以添加不上
[dict1 setValue:@"lisi" forKey:@"ls"]; // ls
[dict1 setValue:@"liuneng" forKey:@"ln"];
NSLog(@"%@",dict1);
3)删除
[dict1 removeObjectForKey:@"ls"];
[dict1 removeAllObjects];
NSLog(@"%@",dict1);
4)修改
[dict1 setObject:@"zhaosi" forKey:@"ls"];
//简写形式
dict1[@"ls"] = @"xxxxx";
NSLog(@"%@",dict1);
5)查找
获取所有的key值
NSArray *arr = [dict1 allKeys];
if([arr containsObject:@"ls"]){
NSLog(@"存在ls的key");
}
十、NSFileManger介绍使用
1.使用介绍
//NSFileManager 用于判断
NSString *filePath = @"/Users/zhaoxiaohu/Desktop/arr.plist";
NSString *filePath2 = @"/";
1) 判断文件是否存在
创建文件管理对象
调用defaultManager 创建一个文件管理的单例对象
单例对象:在程序运行期间,只有一个对象存在
NSFileManager *fm = [NSFileManager defaultManager];
// YES 存在 NO 不存在
BOOL isYES = [fm fileExistsAtPath:filePath];
NSLog(@"-->%d",isYES);
if(isYES){
BOOL isDir;
2) 判断是否是一个目录
[fm fileExistsAtPath:filePath isDirectory:&isDir];
if (isDir) {
NSLog(@"这是一个目录");
}else{
NSLog(@"这不是一个目录");
}
}
3) 判断文件是否可读
isYES = [fm isReadableFileAtPath:filePath];
4) 是否可写
isYES = [fm isWritableFileAtPath:filePath2];
5) 是否可删除
isYES = [fm isDeletableFileAtPath:filePath2];
NSLog(@"-->%d",isYES);
2.深入用法(一)
//创建文件对象
NSFileManager *fm = [NSFileManager defaultManager];
NSString *filePath =@"/Users/zhaoxiaohu/Desktop/arr.plist";
NSString *dirPath = @"/Users/zhaoxiaohu/Desktop/a";
1)如何获取文件的信息(属性)
NSDictionary *dict = [fm attributesOfItemAtPath:filePath error:nil];
NSLog(@"%@",dict);
NSLog(@"%@,%@",[dictobjectForKey:@"NSFileOwnerAccountName"],dict[@"NSFileOwnerAccountName"]);
2)获取指定目录下文件及子目录
//使用递归的方式获取当前目录及子目录下的所有的文件及文件夹
NSArray *subPaths = [fm subpathsAtPath:dirPath];
//subpathsOfDirectoryAtPath 不是使用递归的方式获取的
subPaths = [fm subpathsOfDirectoryAtPath:dirPath error:nil];
NSLog(@"subPaths = %@",subPaths);
3)获取指定目录下的文件及目录信息(不在获取后代路径)
subPaths = [fm contentsOfDirectoryAtPath:dirPath error:nil];
NSLog(@"subPaths = %@",subPaths);
深入用法(二)
//创建文件管理对象
NSFileManager *fm = [NSFileManager defaultManager];
//如何创建目录 (路径 :/Users/zhaoxiaohu/Desktop/aaa)
NSString *createDirPath = @"/Users/zhaoxiaohu/Desktop/aaa/ccc/bbb/love.txt";
fmcreateDirectoryAtPath:@"路径" withIntermediateDirectories:YES/NO 创建路径的时候,YES自动创建路径中缺少的目录,NO的不会创建缺少的目录attributes:属性的字典 error:错误对象
BOOL isYES = [fmcreateDirectoryAtPath:createDirPath withIntermediateDirectories:YESattributes:nil error:nil];
if (isYES) {
NSLog(@"成功");
}
如何创建文件
NSString *str = @"每当我错过一个女孩,我就向山上放一块砖,于是就有了长城";
writeToFile
fm createFileAtPath:@"路径" contents:NSData类型的数据 attributes:文件的属性的字典
创建NSData? 是一个处理二进制数据的类
NSString -----> NSData
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
BOOL isYes;
// createFileAtPath 创建文件
isYes = [fm createFileAtPath:createDirPath contents:dataattributes:nil];
NSLog(@"isYes = %d",isYes);
如何copy文件
NSString *targetPath =@"/Users/zhaoxiaohu/Desktop/aaa/ccc/love.txt";
[fm copyItemAtPath:createDirPath toPath:targetPath error:nil];
NSString *targetPath =@"/Users/zhaoxiaohu/Desktop/aaa/love.txt";
//如何移动文件
[fm moveItemAtPath:createDirPath toPath:targetPath error:nil];