Objective-C中NSArray的基本用法示例

时间:2022-09-20 08:30:17

NSArray的排序

复制代码 代码如下:

+ (id)studentWithFirstName:(NSString *)firstName lastName:(NSString *)lastName{ 
     
    Student *stu = [[Student alloc] init]; 
     
    stu.firstName = firstName; 
    stu.lastName = lastName; 
     
    return stu; 

 
+ (id)studentWithFirstName:(NSString *)firstName lastName:(NSString *)lastName bookName:(NSString *)bookName{ 
 
    Student *stu = [Student studentWithFirstName:firstName lastName:lastName]; 
     
    stu.book = [Book bookWithName:bookName]; 
     
    return stu; 
 

 
- (NSComparisonResult)compareStudent:(Student *)stu{ 
     
    NSComparisonResult result = [self.firstName compare:stu.firstName]; 
     
    if (result == NSOrderedSame) { 
        result = [self.lastName compare:stu.lastName]; 
    } 
     
    return result; 
     

 
- (NSString *)description{  
  
    //return [NSString stringWithFormat:@" %@ %@ %@",self.firstName,self.lastName,self.book.name]; 
    return [NSString stringWithFormat:@" %@ %@ %@",self.firstName,self.lastName,_book.name]; 

 
 
#pragma mark 3.NSArray排序1 
void arraySort1(){ 
     
    NSArray *array = [NSArray arrayWithObjects:@"2",@"3",@"1",@"4", nil nil]; 
     
    // 指定系统自带规定的比较方法compare: 
    NSArray *array2 = [array sortedArrayUsingSelector:@selector(compare:)]; 
    NSLog(@"%@",array2); 
     

 
#pragma mark 3.NSArray排序2 
void arraySort2(){  
      
    Student *stu1 = [Student studentWithFirstName:@"hu" lastName:@"mingtao"]; 
    Student *stu2 = [Student studentWithFirstName:@"zhu" lastName:@"wenpeng"]; 
    Student *stu3 = [Student studentWithFirstName:@"zhao" lastName:@"weisong"]; 
    Student *stu4 = [Student studentWithFirstName:@"hu" lastName:@"junpeng"]; 
     
    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4, nil nil]; 
     
    // 类似JAVA中得compareTo,自己定义比较方式,但是一定要实现compare方法 
    NSArray *array2 = [array sortedArrayUsingSelector:@selector(compareStudent:)]; 
     
    NSLog(@"%@",array2); 
 

 
#pragma mark 3.NSArray排序3-Block排序 
void arraySort3(){ 
     
    Student *stu1 = [Student studentWithFirstName:@"hu" lastName:@"mingtao"]; 
    Student *stu2 = [Student studentWithFirstName:@"zhu" lastName:@"wenpeng"]; 
    Student *stu3 = [Student studentWithFirstName:@"zhao" lastName:@"weisong"]; 
    Student *stu4 = [Student studentWithFirstName:@"hu" lastName:@"junpeng"]; 
     
    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4, nil nil]; 
     
    NSArray *array2 = [array sortedArrayUsingComparator:^NSComparisonResult(Student *obj1, Student *obj2) { 
        NSComparisonResult result = [obj1.firstName compare:obj2.firstName]; 
         
        if (result == NSOrderedSame) { 
            result = [obj1.lastName compare:obj2.lastName]; 
        }  
          
        return result; 
    }]; 
     
    NSLog(@"%@",array2); 
 
     
}  
 
#pragma mark 4.NSArray排序4-高级排序 
void arraySort4(){ 
     
    Student *stu1 = [Student studentWithFirstName:@"hu" lastName:@"mingtao" bookName:@"lianai"]; 
    Student *stu2 = [Student studentWithFirstName:@"zhu" lastName:@"wenpeng" bookName:@"tianshi"]; 
    Student *stu3 = [Student studentWithFirstName:@"zhao" lastName:@"weisong" bookName:@"love"]; 
    Student *stu4 = [Student studentWithFirstName:@"hu" lastName:@"junpeng" bookName:@"qingren"]; 
     
    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4, nil nil]; 
     
    // 1.先按照书名进行排序 
    NSSortDescriptor *bookNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"book.name" ascending:YES]; 
    // 2.先按照姓进行排序 
    NSSortDescriptor *firstNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES]; 
    // 3.先按照名进行排序 
    NSSortDescriptor *lastNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]; 
 
    NSArray *array2 = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:bookNameDesc,firstNameDesc,lastNameDesc, nil nil]]; 
     
    NSLog(@"%@",array2);  
      
     
}

 


NSArray的一些用法
NSArray  只允许装OC对象,并且不能装空值,空代表数组元素的结束

复制代码 代码如下:


#pragma mark - NSArray的基本用法
   // 创建一个空数组
      NSArray *array = [NSArray array];
   // 创建有一个元素的数组
      array = [NSArray arrayWithObject:@"123"];
    // 创建有多个元素的数组
      array = [NSArray arrayWIthObjects:@"a",@"b",nil ];//不能装nil空指针,空值代表数组元素结束
    // 将一个数组赋值给一个数组
    + (instancetype)arrayWithArray:(NSArray *)array;
    // 获取元素的个数
       int count = [array count]; //和 count = array.count; 相同,都是调用get方法
    // 是否包含一个元素
      - (bool)containsObject:(id)anObject;
    // 返回最后一个元素
       - (id) lastObject;
     // 获取index位置的元素
        - (id)objectAtIndex:(NSUInteger) index;
     // 获取元素的位置
        - (NSUInteger) indexOfObject:(id)anObject;
     // 在range范围内查找元素的位置
        - (NSUInteger) indexofObject:(id)anObject inRange:(NSRange)range;
     // 比较两个集合内容是否相同
        - (Bool) isEqualToArray:(NSArray *)otherArray;
     // 返回两个集合中第一个相同的对象元素
        - (id) firstObjectCommonWithArray:(NSArray *)otherArray;

 

#pragma mark - NSArray的高级用法
        //让集合里面的所有元素都执行aSelector这个方法
           - (void)makeObjectsPerformSelector:(SEL)aSelector;
        //让集合里面的所有元素都执行aSelector这个方法,给这个方法添加参数,但是只支持一个参数
           - (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument
        //添加一个元素,返回一个新的NSArray(方法调用者本身没有发生变化)
           - (NSArray *)arrayByAddingObject:(id)anObject
       //添加otherArray的所有元素,返回一个新的NSArray(方法着本身没有改变)
           - (NSArray *) arrayByAddingObjectsFromArray:(NSArray *) otherArray;
       //截取range范围的数组
           - (NSArray *) subarrayWithRange:(NSRenge)range;
      //用separator做拼接符,拼接成一个字符串
           - (NSString *) componentsJoinedByString:(NSString *)separator
      //将NSArray持久化到文件中去
           - (Bool) writeToFile:(NSString *)path atomically:(Bool)useAuxiliaryFile

#pragma mark - NSArray的遍历
     // 方法一:普通遍历(利用for循环)
       void arrayFor1(){
        NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
        int count = array.count;
        for(int i=0; i<count; i++){
              id obj = [array objectAtIndex:i];
             NSLog(@"%i-%@",i, obj);
        }
       }

     // 方法二:快速遍历
       void arrayFor2(){
           NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
           int count = array.count;
           int i=0;
           for(id obj in array){
                NSLog(@"%i-%@",i, obj);
                i++;
           }
         }

     // 方法三:利用block遍历
          void arrayFor3(){
               NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
               [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                       NSLog(@"%zi->%@",idx, obj);
                        //  *stop = YES; //改变外边的Bool,终止遍历
                  }];
             }

    // 方法四:利用迭代器
 先介绍一下-->NSEnumerator迭代器:集合的迭代器,可以用于遍历集合元素,NSArray 有相应的方法来获取迭代器
                  //获取一个正序遍历的迭代器
                     - (NSEnumerator *) objectEnumerator;
                 //获取一个反序遍历的迭代器
                     - (NSEnumerator *) reverseObjectEnumerator;
                @常用方法:
                 //获取下一个元素
                    - (id) nextObject;
                 //获取所有的元素
                    - (NSArray *) allObjects
          void arrayFor4(){
                   NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
                   NSEnumerator *enumerator = [array objectEnumerator];// 返回数组的迭代器
                   //如果放到遍历之后,则取到空,原因是,遍历完了,就没值了
                   NSArray *array2 = [enumerator allObjects];
                   NSLog(@"array2=%@", array2);
   
                 //获取下一个需要遍历的元素
                   id obj = nil;
                   while (obj = [enumerator nextObject]) {
                         NSLog(@"obj=%@", obj);
                   }
                  }

 


使用block 块遍历整个数组。这个block 需要三个参数,id obj 表示数组中的元素。 
NSUInteger idx 标示元素的下标, 
boolbool *stop 是一个bool类型的参数。 官方描述如下: 
A reference to a Boolean value. The block can set the value to YES to stop further processing of the array.  
The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. 
- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx,BOOLBOOL *stop))block  
调用例子如: 
 

复制代码 代码如下:
 
NSArray *array = [NSArray arrayWithObjects:@"wendy",@"andy",@"tom",@"test", nil nil];  
  
  
   [array enumerateObjectsUsingBlock:^(id str,NSUInteger index, BOOL* te){ 
       NSLog(@"%@,%d",str,index); 
   }]; 


同上面的方法一项,区别在于,这里多添加了一个参数,用来标示 是从前向后遍历,还是从后往前遍历。 
- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, NSUInteger idx,BOOLBOOL *stop))block 
调用例子如下: 

复制代码 代码如下:

NSArray *array = [NSArray arrayWithObjects:@"wendy",@"andy",@"tom",@"test", nil nil]; 
 
 
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id str,NSUInteger index, BOOL* te){ 
        NSLog(@"%@,%d",str,index);  
    }];