ios ——OC——NSArray的用法

來源:互聯網
上載者:User

標籤:

NSArray  從本質上講,NSArray 就是一個存放對象的容器。NSArray只能儲存Objective-C 對象,而不能儲存C語言中的基礎資料型別 (Elementary Data Type),比如:int,flot,指標等。 在使用NSArray時,需特別注意,必須以nil 結尾。以此來代表結束。NSArray 建立的是靜態數組,一旦建立之後,就再也不能添加和刪除數組中的對象了。  1.NSArray的建立:類方法建立數組:
  1. NSArray *array1 = [NSArray arrayWithObject:@"obj"];  
  2. NSArray *array2 = [NSArray arrayWithObjects:@"obj1", @"obj2", @"obj3", nil];  
  3. NSArray *array3 = [NSArray arrayWithArray:array2];  
執行個體方法建立數組:NSArray *array4 = [[NSArray alloc] initWithObjects:@"AAA", @"bbb", nil];  NSArray *arr = [NSArray array];//初始化一個空的數組(不常用);        NSArray *arr1 = [NSArray arrayWithObject:@"123"];        NSLog(@"%@",arr1);//初始化一個包含一個元素的數組;        NSArray *arr2 = [NSArray arrayWithObjects:@"zhangyu",@"zhangdawei",@"liuhuan" ,nil];//初始化多個元素的數組,元素之間用逗號隔開,最後以nil結束;        NSArray *arr3 = @[@"123",                          @"456",                         @"789"                          ];//初始化多個元素時數組元素之間用逗號隔開,注意,最後一個元素後面不要加逗號(如果元素是一個類的對象則不用雙引號)。 2.NSArray的使用:(1)求數組的長度:        NSUInteger count = arr3.count;//數組元素的個數(數組的長度);        NSLog(@"數組元素的個數:%zi",count);       NSLog(@"數組元素的個數:%zi",arr3.count); array == nil 和 [array count] == 0前者為true的時候表示這個對象是nil,是一個空的指標,它甚至沒有被建立出來。後者為true表示這個對象為nil或者沒有任何元素。 (2)取數組中的元素        [arr3 firstObject];//數組的第一個元素
        [arr3 lastObject];//數組的最後一個元素
        [arr3 objectAtIndex:2];//指定位置上的數組元素
        long int i = [arr3 indexOfObject:@"123"];//擷取某個元素在數組中的位置(資料類型為long/long int/NSUInteger(Integer 整數 整體 完整的事物));        NSLog(@"i=%ld",i);(3)判斷數組中是否包含某個元素        BOOL flag = [arr3 containsObject:@"123"];//判斷數組中是否包含某個元素 (1包含, 0不包含)        NSLog(@"flag=%d",flag); (4)數組的遍曆  (很重要)<1>for迴圈遍曆(最常用)        for(int i = 0;i < arr3.count;i++)
        {
            NSString *str = arr3[i];
            NSLog(@"%@",str);
           //id obj = [arr3 objectAtIndex:i];
           //NSLog(@"%@",obj);        }<2>使用列舉程式進行遍曆        NSEnumerator *e = [arr3 objectEnumerator];//擷取數組所有元素的列舉程式
        //[e nextObject]第一次遍曆,nextobject指向數組的首元素,當取值結束以後,再指向下一個元素,直到取完最後一個元素,此時nextObject指向nil,值為0,遍曆結束
        id obj;
        while(obj=[e nextObject])            NSLog(@"%@",obj);<3>快速枚舉(最快速,但沒辦法使用下標)(不需要 NSEnumerator *e = [arr3 objectEnumerator];直接用for進行遍曆)        for(id obj1 in arr3)            NSLog(@"%@",obj1);<4>數組存放自訂類的對象(定義一個student類和name,number屬性 ,初始化5個對象)        Student *stu1 = [[Student alloc]init];
        stu1.name = @"張一";
        stu1.number = 201501;
        Student *stu2 = [[Student alloc]init];
        stu2.name = @"張二";
        stu2.number = 201502;
        Student *stu3 = [[Student alloc]init];
        stu3.name = @"張三";
        stu3.number = 201503;
        Student *stu4 = [[Student alloc]init];
        stu4.name = @"張四";
        stu4.number = 201504;
        Student *stu5 = [[Student alloc]init];
        stu5.name = @"張五";
        stu5.number = 201505;
        NSArray *studentarr2 [email protected][stu1,
                                stu2,
                                stu3,
                                stu4,
                                stu5
                                ];
        for (int i = 0; i < studentarr2.count; i++) {            id stu = studentarr2[i];            //判斷某個對象是否是某個類,多用於處理類型不確定的情況
            if ([stu isKindOfClass:[Student class]]) {
                NSLog(@"姓名:%@ 學號:%d",[stu name],[stu number]);
                          }                 }啟動並執行結果: 姓名:張一 學號: 201501
姓名:張二 學號: 201502
姓名:張三 學號: 201503
姓名:張四 學號: 201504 姓名:張五 學號: 201505 (5)排序(從小到大)       NSArray *arr4  = @[@"6",@"9",@"8",@"1"];        NSArray *arr5 = [arr4 sortedArrayUsingSelector:@selector(compare:)];(用於數組中的元素不是對象(是字串的情況!))        NSLog(@"%@",arr5); 加入先建立一個Student類,初始化四個對象stu1,stu2,stu3,stu4放入數組,按要求進行排序排序方法定義:-(NSComparisonResult)compareWithScore:(Student *)stu;排序方法實現:-(NSComparisonResult)compareWithScore:(Student *)stu
{
    NSComparisonResult result;
    if(self.score < stu.score)
        result = 1;
    else result = -1;
    return result;}主程式: NSArray *studentarr = @[    stu1,                             stu2,
                             stu3,                             stu4        //數組元素是某個類的對象的排序 ];        //第一種方法:
        NSArray *scorearr1 = [studentarr sortedArrayUsingSelector:@selector(compareWithScore:)];
        NSLog(@"scorearr1=%@",scorearr1);
        //第二種方法:
        NSArray *scorearr2 = [studentarr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSComparisonResult result = -1;
           
            if ([obj1 score] < [obj2 score])
                result = 1;
                return result;
           
        }];
        NSLog(@"scorearr2=%@",scorearr2);
        //第三種方法(描述方法):
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO  ];
        NSArray *desarr = @[sort];
        NSArray *scorearr3 = [studentarr sortedArrayUsingDescriptors:desarr];        NSLog(@"scorearr3=%@",scorearr3);       // 根據學生的成績由低到高排序,如果成績一樣,則按照年齡從小到大排序*(描述方法)        NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:YES  ];
        NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES  ];

        NSArray *desarr1 = @[sort1,sort2];
        NSArray *scoreagearr = [studentarr sortedArrayUsingDescriptors:desarr1];        NSLog(@"scoreagearr=%@",scoreagearr); 

ios ——OC——NSArray的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.