IOS开发之OC基础学习笔记(中)

文章目录

      • 1. Foundation-结构体
      • 2. Foundation-NSString
        • NSString的创建
        • 从文件、网络读取文本
        • 字符串的导出
        • 大小写转换
        • 字符串的比较
        • 字符串的搜索
        • 字符串的截取
        • 与路径相关
        • 拓展名处理
        • 其他用法
      • 3. Foundation-NSMutableString
        • 可变字符串的创建
      • 4. Foundation-NSArray
        • 创建一个数组
        • 数组的简单使用
        • 数组的内存管理
        • 给数组里面的元素发送消息
        • 遍历数组
        • 派生出新的数组
        • 数组的其他用法
        • 数组排序
      • 5. Foundation-NSMutableArray
        • 用法如下
        • NSMutableArray的内存管理

  • 该笔记源自对传智播客《IOS开发快速入门视频》的学习
  • 如有侵权,请联系本人删除。
  • 都是比较基础的OC知识,中高级开发者可以忽略本文
  • 很多重要内容在代码注释中

1. Foundation-结构体

用法参考:
NSRange range = NSMakeRange(8, 10);
CGPoint p = NSMakePoint(10, 9);
NSPoint p = CGPointMake(8, 9);
NSSize size = NSMakeSize(90, 80);
CGSize size = CGSizeMake(10, 8);
NSRect rect = = NSMakeRect(10, 10, 80, 80);
CGRect rect = CGRectMake(8, 9, 10, 90);
类型打印方式:NSLog(@"%@", NSStringFromRect(rect));

2. Foundation-NSString

NSString的创建

// 这种方式创建出来的字符串是不需要释放的
NSString *str1 = @"A String!";
    
NSString *str2 = [[NSString alloc] init];
str2 = @"A String!";
[str2 release];

//将c语言的字符转NSString
NSString *str4 = [[NSString alloc] initWithUTF8String:"A String!"];
[str4 release];
str4 = [NSString stringWithUTF8String:"A String!"];

str5 = [NSString stringWithFormat:@"My age is %i and height is %.2f", 19, 1.55f];

从文件、网络读取文本

NSString *path = @"/Users/apple/Desktop/test.txt";
// 这个方法已经过期,不能解析中文
// NSString *str1 = [NSString stringWithContentsOfFile:path];

// 定义一个NSError变量
NSError *error;
// 指定字符串编码为UTF-8: NSUTF8StringEncoding
NSString *str1 = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error == nil) { // 没有错误信息
    NSLog(@"读取文件成功:%@", str1);
} else {
    NSLog(@"读取文件失败:%@", error);
}

NSURL *url = [NSURL URLWithString:@"file:///Users/apple/Desktop/test.txt"];
NSString *str2 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@", str2);

NSURL *url2 = [NSURL URLWithString:@"http://www.baidu.com"];
NSString *str3 = [NSString stringWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@", str3);

字符串的导出

NSString *str = @"123456我是字符串!!!!";
// 如果文件不存在,会自动创建文件
// 如果文件夹不存在,会直接报错
NSString *path = @"/Users/apple/Desktop/abc.txt";

NSError *error;
// 编码指定错误也会报错
// YES代表要进行原子性操作,也就是会创建一个中间的临时文件
[str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
    // [error localizedDescription]会返回主要的错误信息
    NSLog(@"写入失败:%@", [error localizedDescription]);//???
} else {
    NSLog(@"写入成功");
}

大小写转换

NSString *str = @"GuangDong";
NSLog(@"大写:%@", [str uppercaseString]);
NSLog(@"小写:%@", [str lowercaseString]);
// 首字母变大写,其他字母变小写
NSLog(@"首字母变大写:%@", [@"aGE" capitalizedString]);

字符串的比较

// 检测字符串的内容是否相同
BOOL result = [@"abc" isEqualToString:@"abc"];
NSLog(@"%i", result);

NSLog(@"'a' =%i ,'A' = %i", 'a','A');
//'a' =97 ,'A' = 65

// NSOrderedAscending  右边的字符串比左边大
// NSOrderedSame  两个字符串的内容相同
// NSOrderedDescending  左边的字符串比右边的大
NSComparisonResult result2 = [@"abc" compare:@"Abc"];
if (result2 == NSOrderedSame) {
    NSLog(@"两个字符串的内容相同");
} else if (result2 == NSOrderedAscending) {
    NSLog(@"右边 > 左边");
} else if (result2 == NSOrderedDescending) {
    NSLog(@"右边 < 左边");
}
//右边 < 左边

字符串的搜索

NSString *str = @"123456456.txt";

NSLog(@"是否以22开头:%i", [str hasPrefix:@"22"]);//0
NSLog(@"是否以txt结尾:%i", [str hasSuffix:@"txt"]);//1

// 搜索字符串
NSRange range = [str rangeOfString:@"456"];
// range.length == 0
if (range.location == NSNotFound) {
    NSLog(@"不能找到");
} else {
    NSLog(@"找到的范围是:%@", NSStringFromRange(range));//{3, 3}
}

// 从尾部开始搜索字符串
range = [str rangeOfString:@"456" options:NSBackwardsSearch];
NSLog(@"从尾部开始搜索:%@", NSStringFromRange(range));//{6, 3}

// 指定范围进行搜索
range = [str rangeOfString:@"456" options:NSBackwardsSearch range:(NSMakeRange(2, 6))];
NSLog(@"指定范围进行搜索:%@", NSStringFromRange(range));//{3, 3}

字符串的截取

NSString *str = @"123456";

// 从索引3开始截取到尾部(包括3)
NSLog(@"%@", [str substringFromIndex:3]);//456

// 从头部开始截取到索引3之前(不包括3)
NSLog(@"%@", [str substringToIndex:3]);//123

// 指定范围进行截取
NSRange range = NSMakeRange(2, 3);
NSLog(@"%@", [str substringWithRange:range]);//345

NSString *str2 = @"a-b-c-d-5";
NSArray *array = [str2 componentsSeparatedByString:@"-"];
NSLog(@"%@", array);//(a,b,c,d,5)

NSString *str3 =  [array objectAtIndex:0];
NSLog(@"%@", str3);//a

与路径相关

// 快速创建一个自动释放的数组
NSMutableArray *components = [NSMutableArray array];
[components addObject:@"Users"];
[components addObject:@"MJ"];
[components addObject:@"Desktop"];
// 将数组中的所有字符串拼接成一个路径
NSString *path = [NSString pathWithComponents:components];
NSLog(@"%@", path);//Users/MJ/Desktop

// 将路径分解成一个数组
NSArray *cmps = [path pathComponents];
NSLog(@"%@", cmps);//(Users,MJ,Desktop)

// path是一个字符串常量,是不可变的
path = @"/users/mj/test";
// 判断是够为绝对路径(依据是前面有无/)
NSLog(@"%i", [path isAbsolutePath]);//1
NSLog(@"最后一个目录:%@", [path lastPathComponent]);//test
// 删除最后一个目录
NSLog(@"%@", [path stringByDeletingLastPathComponent]);///users/mj
// 在最后面拼接一个目录
NSLog(@"%@", [path stringByAppendingPathComponent:@"abc"]);///users/mj/test/abc

拓展名处理

NSString *str = @"/User/MJ/test.txt";

NSLog(@"拓展名:%@", [str pathExtension]);//txt
// 删除拓展名
NSLog(@"%@", [str stringByDeletingPathExtension]);///User/MJ/test
// 添加拓展名
NSLog(@"%@", [@"abc" stringByAppendingPathExtension:@"mp3"]);//abc.mp3

其他用法

//NSString 转int
NSString *str = @"12";
int a = [str intValue];
NSLog(@"%i", a);//12

// 计算字数,不是计算字符数
NSLog(@"length=%zi", [@"我是字符串123" length]);//length=8

// 取出对应的字符
unichar c = [@"abc" characterAtIndex:0];
NSLog(@"%c", c);

// 返回C语言中的字符串
const char *s = [@"abc" UTF8String];
NSLog(@"%s", s);//abc

3. Foundation-NSMutableString

可变字符串的创建

// 预先分配10个字数的存储空间
NSMutableString *str = [[NSMutableString alloc] initWithCapacity:10];

//this is ok
NSMutableString *str = [[NSMutableString alloc]init];

// 设置字符串内容
[str setString:@"1234"];

// 拼接一个字符串
[str appendString:@"567"];
// 拼接字符串
[str appendFormat:@"age is %i and height is %.2f", 27, 1.55f];
//1234567age is 27 and height is 1.55

// 替换字符串
NSRange range = [str rangeOfString:@"height"];
//NSRange range = NSMakeRange(7, 3);
[str replaceCharactersInRange:range withString:@"no"];
//1234567age is 27 and no is 1.55

// 插入字符串
[str insertString:@"abc" atIndex:2];
//12abc34567age is 27 and no is 1.55

// 删除字符串
range = [str rangeOfString:@"age"];
[str deleteCharactersInRange:range];

NSLog(@"%@", str);
//12abc34567 is 27 and no is 1.55

// 释放对象
[str release];

4. Foundation-NSArray

创建一个数组

// 创建一个空的数组
NSArray *array = [NSArray array];

// 创建有1个元素的数组
array = [NSArray arrayWithObject:@"123"];

// 创建有多个元素的数组
array = [NSArray arrayWithObjects:@"a", @"b", @"c", nil]; //count = 3

int count = [array count];
// count = array.count;
NSLog(@"%i", count);

数组的简单使用

NSObject *obj = [[NSObject alloc] init];
NSArray *array = [NSArray arrayWithObjects:@"a", @"b", @"c" , obj, nil];
// 判断是否包含了某个元素
if ([array containsObject:@"a"]) {
    NSLog(@"包含了字符串a");
}

NSString *last = [array lastObject];
NSLog(@"last=%@", last);//

NSString *str = [array objectAtIndex:1];
NSLog(@"%@", str);

int index = [array indexOfObject:@"c"];
NSLog(@"index=%i", index);

[obj release];

数组的内存管理

Student *stu1 = [[Student alloc] init];
Student *stu2 = [[Student alloc] init];
Student *stu3 = [[Student alloc] init];

NSLog(@"stu1:%zi", [stu1 retainCount]);//1

// 当把一个对象塞进数组中时,这个对象的计数器会加1,也就是说数组会对它做一次retain操作
NSArray *array = [[NSArray alloc] initWithObjects:stu1, stu2, stu3, nil];

NSLog(@"stu1:%zi", [stu1 retainCount]);//2

NSLog(@"count=%zi", array.count);//3

[stu1 release];//1
[stu2 release];
[stu3 release];

// 数组被销毁的时候,会对内部的所有元素都做一次release操作
[array release];//0

给数组里面的元素发送消息

Student *stu1 = [Student student];
Student *stu2 = [Student student];
Student *stu3 = [Student student];

NSArray *array = [NSArray arrayWithObjects:stu1, stu2, stu3, nil];
// 让数组里面的所有对象都调用test方法
 [array makeObjectsPerformSelector:@selector(test)];
// 让数组里面的所有对象都调用tes2t方法,并传递一个
[array makeObjectsPerformSelector:@selector(test2:) withObject:@"123"];

遍历数组

Student *stu1 = [Student student];
NSArray *array = [NSArray arrayWithObjects:stu1, @"1", @"2", @"3", nil];
//方法1
int count = array.count;
for (int i = 0; i
//1-1

//方法4
// 获取数组的迭代器
// NSEnumerator *enumerator = [array objectEnumerator];
// 反序迭代器(从尾部开始遍历元素)
NSEnumerator *enumerator = [array reverseObjectEnumerator];

// allObjects是取出没有被遍历过的对象
NSArray *array2 = [enumerator allObjects];
NSLog(@"array2:%@", array2);

// 获取下一个需要遍历的元素
id obj = nil;
while (obj = [enumerator nextObject]) {
    NSLog(@"obj=%@", obj);
}

派生出新的数组

NSArray *array = [NSArray arrayWithObjects:@"1", @"2", nil];

NSArray *array2 = [array arrayByAddingObject:@"3"];

NSArray *array3 = [array arrayByAddingObjectsFromArray:[NSArray arrayWithObjects:@"4", @"5", nil]];

NSLog(@"array:%@", array);//(1,2)
NSLog(@"array2:%@", array2);//(1,2,3)
NSLog(@"array3:%@", array3);//(1,2,4,5)

NSArray *array4 = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
NSRange range = NSMakeRange(1, 2);
NSArray *array5 = [array4 subarrayWithRange:range];
NSLog(@"array5:%@", array5);//(2,3)

数组的其他用法

NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
// 1-2-3-4
// 利用分隔符-拼接所有的数组元素
NSString *str = [array componentsJoinedByString:@"-"];
NSLog(@"%@", str);

// 将一个数组写入文件(生成的是一个xml文件)
NSString *path = @"/Users/apple/Desktop/array.xml";
[array writeToFile:path atomically:YES];

path = @"/Users/apple/Desktop/array.txt";
//上面写入的xml文件,此处也可以直接读取
// 从文件中读取数组内容(文件有严格的格式要求),格式如下
//
//	1
//	2
//	3
//	4
//

NSArray *array2 = [NSArray arrayWithContentsOfFile:path];
NSLog(@"array2:%@", array2);

数组排序

  • 排序1
NSArray *array = [NSArray arrayWithObjects:@"2", @"3", @"1", @"4", nil];
// 返回一个排好序的数组,原来数组的元素顺序不会改变
// 指定元素的比较方法:compare:
// compare two NSDecimalNumbers
NSArray *array2 = [array sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"array2:%@", array2);//(1,2,3,4)
  • 排序2、3
Student *stu1 = [Student studentWithFirstname:@"MingJie" lastname:@"Li"];
Student *stu2 = [Student studentWithFirstname:@"LongHu" lastname:@"Huang"];
Student *stu3 = [Student studentWithFirstname:@"LianJie" lastname:@"Li"];
Student *stu4 = [Student studentWithFirstname:@"Jian" lastname:@"Xiao"];
NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4, nil];

方法1
// 指定排序的比较方法
NSArray *array2 = [array sortedArrayUsingSelector:@selector(compareStudent:)];
//compareStudent 是什么,见下一个代码块

//方法2
// 利用block进行排序
NSArray *array2 = [array sortedArrayUsingComparator:
 ^NSComparisonResult(Student *obj1, Student *obj2) {
     // 先按照姓排序
     NSComparisonResult result = [obj1.lastname compare:obj2.lastname];
     // 如果有相同的姓,就比较名字
     if (result == NSOrderedSame) {
         result = [obj1.firstname compare:obj2.firstname];
     }
     
     return result;
}];

NSLog(@"array2:%@", array2);
//("[Huang LongHu-(null)]","[Li LianJie-(null)]","[Li MingJie-(null)]","[Xiao Jian-(null)]")

其中compareStudent是Student的一个方法,如下:
- (NSComparisonResult)compareStudent:(Student *)stu {
    // 先按照姓排序
    NSComparisonResult result = [self.lastname compare:stu.lastname];
    // 如果有相同的姓,就比较名字
    if (result == NSOrderedSame) {
        result = [self.firstname compare:stu.firstname];
    }
    
    return result;
}
  • 排序4
Student *stu1 = [Student studentWithFirstname:@"MingJie" lastname:@"Li" bookName:@"book1"];
Student *stu2 = [Student studentWithFirstname:@"LongHu" lastname:@"Huang" bookName:@"book2"];
Student *stu3 = [Student studentWithFirstname:@"LianJie" lastname:@"Li" bookName:@"book2"];
Student *stu4 = [Student studentWithFirstname:@"Jian" lastname:@"Xiao" bookName:@"book1"];
NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4, nil];

// 1.先按照书名进行排序
// 这里的key写的是@property的名称
NSSortDescriptor *bookNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"book.name" ascending:YES];
// 2.再按照姓进行排序
NSSortDescriptor *lastnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"lastname" ascending:YES];
// 3.再按照名进行排序
NSSortDescriptor *firstnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"firstname" ascending:YES];
// 按顺序添加排序描述器
NSArray *descs = [NSArray arrayWithObjects:bookNameDesc, lastnameDesc, firstnameDesc, nil];

NSArray *array2 = [array sortedArrayUsingDescriptors:descs];

NSLog(@"array2:%@", array2);
//("[Li MingJie-book1]","[Xiao Jian-book1]","[Huang LongHu-book2]","[Li LianJie-book2]")

5. Foundation-NSMutableArray

用法如下

NSMutableArray *array = [NSMutableArray arrayWithObject:@"1"];
// 添加元素
[array addObject:@"2"];
[array addObject:@"3"];

//移除元素
[array removeObject:@"2"];
[array removeLastObject];
[array removeAllObjects];

//替换元素
[array replaceObjectAtIndex:1 withObject:@"4"];

//排序
[array sortUsingSelector:@selector(compare:)];
//此处array发生变化,区别NSArray

NSMutableArray的内存管理

NSMutableArray *array = [[NSMutableArray alloc] init];

Student *stu1 = [[Student alloc] init];// stu1:1
stu1.age = 10;

Student *stu2 = [[Student alloc] init];// stu2:1
stu2.age = 20;

// 对被添加的元素做一次retain操作,计数器+1
[array addObject:stu1]; // stu1:2
[array addObject:stu2]; // stu2:2

NSLog(@"add->stu1:%zi", [stu1 retainCount]);

// 对被删除的元素做一次release操作,计数器-1
[array removeObject:stu1]; // stu1:1

NSLog(@"remove->stu1:%zi", [stu1 retainCount]);

// 释放学生
[stu1 release]; // stu1:0
[stu2 release]; // stu2:1

// 当数组被释放的时候,会对所有的元素都做一次release操作
[array release]; // stu2:0

IOS开发之OC基础学习笔记(上)
IOS开发之OC基础学习笔记(中)
IOS开发之OC基础学习笔记(下)

你可能感兴趣的:(IOS学习笔记)