不变数组 NSArray
//1.使用实例方法创建数组
NSArray *array1 = [[NSArray alloc]initWithObjects:@"1", @"fgd", @"3", nil];
NSLog(@"%@",array1);
//2.使用类方法创建数组
NSArray *array2 = [NSArray arrayWithObjects:@"4", @"5", @"6", nil];
NSLog(@"%@", array2);
//3.获取数组元素个数
NSUInteger count = [array1 count];
NSLog(@"%ld", count);
//4.根据索引值获取对象
NSString *str = [array1 objectAtIndex:1];
NSLog(@"%@", str);
//5.根据对象获取索引值
NSUInteger index = [array1 indexOfObject:@"3"];
NSLog(@"%ld", index);
//6.遍历
for (int i = 0; i < [array1 count]; i ++) {
NSString *str = [array1 objectAtIndex:i];
NSLog(@"遍历结果:%@", str);
}
//快速遍历forin
for (NSString *str in array1) {
NSLog(@"快速遍历:%@", str);
}
//数组中使用枚举器 这个是forin得原型
NSArray *a = [NSArray arrayWithObjects:@"dsdf", @"gdsh", @"qwqe", nil];
NSEnumerator *enumerator = [a objectEnumerator];
NSString *str2 = nil;
while (str2 = [enumerator nextObject]) {
NSLog(@"str2 : %@", str2);
}
//NSArray排序
NSArray *a = [NSArray arrayWithObjects:@"12", @"78", @"45", @"qwe", @"9", nil];
NSLog(@"排序前:%@", a);
//按字符串排序
// a = [a sortedArrayUsingSelector:@selector(compare:)];
//按数字排序
a = [a sortedArrayUsingFunction:intSort context:NULL];
NSLog(@"排序后:%@", a);
//Block排序
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *stu1 = [[Student alloc]initWithName:@"zhangsan" withAge:20];
Student *stu2 = [[Student alloc]initWithName:@"lisi" withAge:26];
Student *stu3 = [[Student alloc]initWithName:@"wangwu" withAge:22];
Student *stu4 = [[Student alloc]initWithName:@"zhaoliu" withAge:25];
Student *stu5 = [[Student alloc]initWithName:@"qianqi" withAge:23];
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:stu1];
[array addObject:stu2];
[array addObject:stu3];
[array addObject:stu4];
[array addObject:stu5];
//按年龄排序
array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// Student *a = (Student *)obj1;
// Student *b = (Student *)obj2;
NSInteger a1 = [obj1 getAge];
NSInteger b2 = [obj2 getAge];
if (a1 > b2) {
return NSOrderedDescending;
} else if (a1 < b2) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}];
for (Student *stu in array) {
NSLog(@"%@", stu);
}
NSLog(@" ");
//按名字排序
array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[obj1 getName] compare:[obj2 getName]];
}];
for (Student *stu1 in array) {
NSLog(@"%@", stu1);
}
}
return 0;
}