欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-07-04 09:37:53
nsarray的排序 复制代码 代码如下: + (id)studentwithfirstname:(nsstring *)firstname lastname:(nss...

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);  
    }];