OC中數組的使用方法


#import  <Foundation/Foundation.h>

int  main( int  argc,  const   char  * argv[])
{
    
//  創建數組
    
NSArray  *arr1 =  nil ;
//    NSLog(@"%p", arr1);
    
NSObject  *obj = [ NSObject   new ];
    arr1 = [
NSArray   arrayWithObjects : @"One" @"Two" @"Three" , obj,  nil ]; // 結束標識,相當於 C 語言的 “\0”
//    NSLog(@"%p", arr1);
    
NSLog ( @"arr1: %@" , arr1);
    
    
//  推薦以下的新語法
    
NSString  *str =  @"Hello" ;
    
NSArray  *arr2 =  @[ @"zhangsan" @"lisi" @"wangwu" @"zhaoliu"  , @"tianqi" , str ] ; // 這樣的方法自己主動在后面加入了 nil
    
NSLog ( @"arr2: %@" , arr2);
    
    
//  訪問數組成員  objectAtIndex
//    NSObject *tmpObj = [arr1 objectAtIndex:3];
    
id  tmpObj = [arr1  objectAtIndex : 3 ];
    
NSLog ( @"tmpObj: %@" , tmpObj);
    
    
//  推薦使用以下的新語法
    tmpObj = arr2[
2 ];
    
NSLog ( @"arr2[2]: %@" , tmpObj);
    
    
//  可變數組
    
NSMutableArray  *firstArr = [ NSMutableArray   arrayWithCapacity : 30 ];
    
//  加入
    [firstArr 
addObject : @"One" ];
    [firstArr 
addObject : @"Two" ];
    [firstArr 
addObject : @"Three" ];
    [firstArr 
addObject : @"Four" ];
    [firstArr 
addObject : @"Five" ];
    
    
NSLog ( @"The Mutable Array: %@" , firstArr);
    
    
NSMutableArray  *secArr = [ NSMutableArray   arrayWithArray :arr2];
    
NSLog ( @"secArr: %@" , secArr);
    
    
//  刪除
    [secArr 
removeObject : @"tianqi" ];
    
NSLog ( @"==secArr: %@" , secArr);
    [secArr 
removeObjectAtIndex : 2 ];
    
NSLog ( @"===secArr: %@" , secArr);
    
    
//  插入
    [secArr 
insertObject : @"wangwu"   atIndex : 2 ]; //id  是對象   index  是位置
    
NSLog ( @"after insert: %@" , secArr);
    
    
//  替換
    
NSObject  *someObj = [ NSObject   new ];
    [secArr 
replaceObjectAtIndex : 4   withObject :someObj];
    
NSLog ( @"after replace: %@" , secArr);

    
    
// C 語言遍歷數組
    
NSUInteger  number = [secArr  count ];
    
for  ( int  i =  0 ; i < number; i++) {
        
id  obj = secArr[i];
        
NSLog ( @"%@" , obj);
    }
    
    
    
//  通過枚舉器來遍歷數組(正着遍歷)
    
NSEnumerator  *enum1 = [secArr  objectEnumerator ];
    
id  obj1;
    
NSLog ( @"*************************" );
    
while  (obj1 = [enum1  nextObject ]) {
        
NSLog ( @"obj1: %@" , obj1);
    }
    
    //  通過枚舉器來遍歷數組(倒着遍歷)    
    NSEnumerator  *enum2 = [secArr  reverseObjectEnumerator ];
    
while  (obj1 = [enum2  nextObject ]) {
        
NSLog ( @"reverse: %@" , obj1);
    }
    
    
NSLog ( @"============================" );
    
//  高速枚舉
    
for  ( id  obj  in  secArr) {
        
NSLog ( @"Fast Enumeration: %@" , obj);
    }
    
    
    
return   0 ;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM