首页 > 代码库 > ios 中NSArray
ios 中NSArray
//
#import <Foundation/Foundation.h>
#import "Animal.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//1. 创建方法
//2. 排序
//3. 取元素
//4. 连接,分隔
//5. 强引用
//6. for...in
Animal *ani = [[Animal alloc] init];
ani.age = 12;
//创建一个有三个元素的OC不可变数组
//不可变数组的元素不能再变
// NSArray *arr1 = @[@12, @"34", ani];
// NSLog(@"%lu", arr1.count);
// NSLog(@"%@", arr1);
//不是修改数组
ani.age = 20;
Animal *ani10 = [[Animal alloc] init];
ani10.age = 5;
Animal *ani11 = [[Animal alloc] init];
ani11.age = 48;
NSArray *arr1 = @[ani, ani10, ani11];
NSLog(@"%@", arr1);
//排序,只需要实现两两之间比较的方法
//SEL
NSArray *arr10 = [arr1 sortedArrayUsingSelector:@selector(myCompare:)];
// NSLog(@"%@", arr10);
//依次执行print
[arr10 makeObjectsPerformSelector:@selector(print)];
//可以传递一个参数
[arr10 makeObjectsPerformSelector:@selector(call:) withObject:@"Zhangsan"];
//产生新数组,并且参数作为最后一个元素
NSArray *arr30 = [arr10 arrayByAddingObject:@"aa"];
NSLog(@"%p, %p", arr10, arr30);
NSString *str10 = @"a.b.c";
//分割字符串
NSArray *arr40 = [str10 componentsSeparatedByString:@"."];
NSLog(@"%@", arr40);
//连接字符串
NSString *str11 = [arr40 componentsJoinedByString:@"<+>"];
NSLog(@"%@", str11);
// NSArray *arr20 = @[@123, @"234", @345];
// [arr20 writeToFile:@"/Users/apple/Desktop/test.plist" atomically:YES];
//
// NSArray *arr21 = [NSArray arrayWithContentsOfFile:@"/Users/apple/Desktop/test"];
// NSLog(@"%@", arr21);
return 0;
NSNumber *num1 = arr1[0];
NSLog(@"%@", num1);
Animal *ani2 = [[Animal alloc] init];
ani2.age = 20;
NSNumber *num2 = @34;
//检查是否包含某个对象
if([arr1 containsObject:num2]) {
NSLog(@"在arr1中");
//获取对象的位置
NSUInteger index = [arr1 indexOfObject:ani2];
NSLog(@"%lu", index);
if (NSNotFound == index) {
NSLog(@"没zhaodao ");
}
}
else {
NSLog(@"不在");
}
return 0;
NSLog(@"%lu", arr1.count);
// ani = nil;
//nil表示参数结束
//数组中不能装nil对象
arr1 = [[NSArray alloc] initWithObjects:@90, ani, @80, nil];
NSLog(@"%@", arr1);
// id cArr[4];
// cArr[0] = @"abc";
// cArr[1] = @"efg";
// cArr[2] = ani;
// cArr[3] = @"xxx";
// arr1 = [[NSArray alloc] initWithObjects:cArr count:4];
// NSLog(@"%@", arr1);
//创建一个数组,并且用arr1中的元素初始化
//实际上数组里装的是对象的指针,数组会对装入其中的对象产生一个强引用
NSArray *arr2 = [NSArray arrayWithArray:arr1];
NSLog(@"%lu", arr2.count);
//根据位置获取对象
// NSLog(@"%@", arr2[1]);
NSLog(@"%@", [arr2 objectAtIndex:arr2.count - 1]);
//获取第0个元素
NSLog(@"%@", [arr2 firstObject]);
//获取最后一个元素
NSLog(@"%@", [arr2 lastObject]);
NSLog(@"------");
for (int i = 0; i < arr2.count; ++i) {
NSLog(@"%@", arr2[i]);
}
//两个类型
//1. 编译时类型,指针的类型
//2. 运行时类型,对象的类型
NSLog(@"+++++");
arr2 = @[@12, ani, @34];
//快速枚举
for (id obj in arr2) {
//检查一个对象是否为NSNumber类型
if ([obj isKindOfClass:[NSNumber class]]) {
NSNumber *num = (NSNumber *)obj;
NSLog(@"%d", num.intValue);
}
else if ([obj isKindOfClass:[Animal class]]){
Animal *animal = (Animal *)obj;
NSLog(@"age: %d", animal.age);
}
// obj.age = 20;
}
ani = nil;
arr1 = nil;
arr2 = nil;
NSLog(@"xxxxxxx");
}
NSLog(@"-----");
return 0;
}
ios 中NSArray