Objective-C中NSArray的基本用法樣本_IOS

來源:互聯網
上載者:User

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 ];//不能裝nilnull 指標,空值代表數組元素結束
    // 將一個數組賦值給一個數組
    + (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);  
    }]; 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.