1. 程式人生 > >IOS SDK詳解之NSArray/NSMutableArray

IOS SDK詳解之NSArray/NSMutableArray

原創Blog,轉載請註明出處

前言:本文會首先講一下本人使用NSArray的幾個小技巧,然後詳解下常用的屬性和方法。

一 NSArray/NSMutableArray簡介

   NSArray儲存的是一組物件的陣列,這些物件是有序的,NSArray內容不可改變,如果需要可改變的使用NSMutableArray,它是NSArray的子類,在Cocoa touch中處於Core Service層。當然,也可以繼承NSArray來自定義自己的陣列,不過這種情況極少,這裡不做講解。通常如果需要Array的其他,建立類別(category足矣)

繼承關係:NSArray->NSObject

遵循協議: NSCopying,NSFastEnumeration,NSObject,NSMutableCopying,NSSecureCoding

  NSMutableArray繼承自NSArray。

繼承關係:NSMutableArray->NSArray->NSObject

遵循協議:NSCopying,NSFastEnumeration,NSObject,NSMutableCopying,NSSecureCoding

二 使用NSArray的小技巧

2.1 快捷建立符號@[]

例如

    NSArray *array = @[@“1",@"2",@"3"];

2.2 firstObject:安全返回第一個元素

取NSArray有兩種方式,用array[0]在陣列為空的時候會報錯,用[array firstObject]即使陣列為空,也不會報錯,會返回nil

同理lastObject也一樣,

2.3 makeObjectsPerformSelector:withObject: 和makeObjectsPerformSelector:讓每個陣列內元素都執行某個SEL,這樣寫就不必再寫個for語句了

2.4 KVC的方式取值,做計算

例如有個陣列:

      NSArray * array = @[
                        @{@"name":@"hwc",
                          @"count":@(10),
                          @"url":@"blog.csdn.net/hello_hwc"
                          },
                        @{@"name":@"baidu",
                          @"count":@(20),
                          @"url":@"www.baidu.com"
                          },
                        @{@"name":@"google",
                          @"count":@(22),
                          @"url":@"www.google.com"
                          }
                        ];
    NSArray * nameArray = [array valueForKeyPath:@"name"];
    NSNumber *sum = [array valueForKeyPath:@"@sum.count"];
    NSNumber *max = [array valueForKeyPath:@"@max.count"];
    NSNumber *min = [array valueForKeyPath:@"@min.count"];
    NSLog(@"NameArray:%@",nameArray.description);
    NSLog(@"Sum:%@",sum.description);
    NSLog(@"max:%@",max.description);
    NSLog(@"min:%@",min.description);

輸出

HwcFoundationExample[1048:42991] NameArray:(
    hwc,
    baidu,
    google
)
2015-01-12 14:10:45.357 HwcFoundationExample[1048:42991] Sum:52
2015-01-12 14:10:45.357 HwcFoundationExample[1048:42991] max:22
2015-01-12 14:10:45.357 HwcFoundationExample[1048:42991] min:10

三 NSArray常用屬性方法詳解

為了更加直觀,通過一個例子來展示,常用的使用屬性和方法幾乎都可以從例子中找到。

NSArray例子

//初始化(Initializing an array)
    NSArray * array = [[NSArray alloc] initWithObjects:@"first",@"thrid",@"Second", nil];
    //查詢(Querying an array)
    NSString * toFindString = @"Second";
    if ([array containsObject:toFindString]) {
        NSUInteger index = [array indexOfObject:toFindString];
        NSLog(@"%@ index is %lu",toFindString,index);
    }
    NSString * firstObject = [array firstObject];
    NSString * lastObject = [array lastObject];
    if (firstObject!=nil) {
        NSLog(@"First object is:%@",firstObject);
    }
    if (lastObject!=nil) {
        NSLog(@"LastObject object is:%@",lastObject);
    }
    //排序(Sort)
    NSArray * anotherArray = @[@"1",@"4",@"3"];
    NSArray * sortedArrayWithSEL = [array sortedArrayUsingSelector:@selector(localizedCompare:)];
    NSArray * sortedArrayWithComparator = [anotherArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSString * str1 = obj1;
        NSString * str2 = obj2;
        if (str1.integerValue > str2.integerValue) {
            return NSOrderedDescending;
        }
        if (str1.integerValue < str2.integerValue) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
    
    if ([sortedArrayWithComparator isEqualToArray:sortedArrayWithSEL]) {
        NSLog(@"The array is same");
    }
    else{
        NSLog(@"The array is not same");
    }
    //與檔案進行操作(Working with file)
    //如果存在則讀到數組裡,如果不存在則寫到檔案裡(If exist read,else write to file)
    NSFileManager * defaultManager = [NSFileManager defaultManager];
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentDirectory = [paths firstObject];
    NSString * fileName = @"TestArray.plist";
    NSString * filePath = [documentDirectory stringByAppendingPathComponent:fileName];
    BOOL fileExist = [defaultManager fileExistsAtPath:filePath];
    if (fileExist) {
        //從檔案讀取
        NSArray * readArray = [NSArray arrayWithContentsOfFile:filePath];
        //遍歷
        [readArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if ([obj isKindOfClass:[NSString class]]) {
                NSString * str = obj;
                NSLog(@"At index:%lu is %@",idx,str);
                if ([str isEqualToString:@"thrid"]) {
                    *stop = YES;
                }
            }
        }];
    }else{
        [anotherArray writeToFile:filePath atomically:YES];
    }
NSMutableArray
    //(初始化)Init
    NSMutableArray* mutableArray = [[NSMutableArray alloc] initWithObjects:@"2",@"3",@"4", nil];
    //(新增物件)Add object
    [mutableArray addObject:@"5"];
    [mutableArray insertObject:@"1" atIndex:0];
    //(刪除物件)Remove object
    [mutableArray removeObject:@"3"];
    [mutableArray removeObjectAtIndex:0];
    [mutableArray removeLastObject];
這段程式碼第一次運算輸出
2015-01-14 19:48:46.499 HwcNSArrayExample[509:7777] Second index is 2
2015-01-14 19:48:46.501 HwcNSArrayExample[509:7777] First object is:first
2015-01-14 19:48:46.501 HwcNSArrayExample[509:7777] LastObject object is:Second
2015-01-14 19:48:46.502 HwcNSArrayExample[509:7777] The array is not same
第二次運算輸出
2015-01-14 19:49:31.135 HwcNSArrayExample[525:8151] Second index is 2
2015-01-14 19:49:31.135 HwcNSArrayExample[525:8151] First object is:first
2015-01-14 19:49:31.136 HwcNSArrayExample[525:8151] LastObject object is:Second
2015-01-14 19:49:31.136 HwcNSArrayExample[525:8151] The array is not same
2015-01-14 19:49:31.136 HwcNSArrayExample[525:8151] At index:0 is 1
2015-01-14 19:49:31.137 HwcNSArrayExample[525:8151] At index:1 is 4
2015-01-14 19:49:31.137 HwcNSArrayExample[525:8151] At index:2 is 3

注意,在使用writeToFile的時候,Array中的物件型別可以是

NSString,NSData,NSDate,NSNumber,NSArray,NSDictionary

不可以是其他型別的物件

至於完整的屬性和方法,見官方文件,還是那句話,一定要能看懂官方文件。