NSMutableArray的常用方法

//

//  main.m

//  mutableArray

//

//  Created by Mr.Juice on 15/4/7.

//  Copyright (c) 2015 Mr.Juice. All rights reserved.

//


#import

#import "Car.h"


int main(int argc, const char * argv[]) {


//    mArray1y *array = @[@"t",@"s"];

//    NSLog(@"array = %@",array);

    

//——————————————————————————可变数组的常用方法——————————————————————————————

    

    //1.创建可变数组

//    NSMutableArray *mArray0 = [[NSMutableArray alloc] init];

    

    //创建数组时,同时为该数组分配5个空间存储元素,当5个空间存满后,会自动扩大

    NSMutableArray *mArray1 = [[NSMutableArray alloc] initWithCapacity:3];


    //2.addObject: 添加一个元素

    Car *car0 = [[Car alloc] init];

    [mArray1 addObject:car0];

    NSLog(@"%ld",[mArray1 count]);


    //3.addObjectsFromArray: arary中所有的元素添加到mArray

    NSMutableArray *marray2 = [[NSMutableArray alloc] initWithCapacity:3];

    Car *car1 = [[Car alloc] init];

    Car *car2 = [[Car alloc] init];

    [marray2 addObject:car0];

    [marray2 addObject:car1];

    [marray2 addObject:car2];

    

    [mArray1 addObjectsFromArray:marray2];

    NSLog(@"%@",mArray1);


    //4.insertObject : 插入元素

    [mArray1 insertObject:car2 atIndex:1];


    //5.replaceObjectAtIndex: 替换元素

    [mArray1 replaceObjectAtIndex:2 withObject:car0];

    

    //6.exchangeObjectAtIndex: 互换两个元素的位置

    [mArray1 exchangeObjectAtIndex:3 withObjectAtIndex:2];


    //7.删除元素

    //removeObjectAtIndex: 根据下标删除

    [mArray1 removeObjectAtIndex:0];

    

    //removeObject: 删除指定对象

    [mArray1 removeObject:car2];

    

    //removeLastObject: 删除最后一个对象

    [mArray1 removeLastObject];

    

    //removeAllObjects: 删除所有元素

    [mArray1 removeAllObjects];

    

    NSLog(@"mArray1 count: %ld",[mArray1 count]);

    

    

    return 0;

}





以下是运行结果:

2015-04-07 22:52:04.836 mutableArray[621:39737] 1

2015-04-07 22:52:04.837 mutableArray[621:39737] (

    "I'm a Car ahaha~",

    "I'm a Car ahaha~",

    "I'm a Car ahaha~",

    "I'm a Car ahaha~"

)

2015-04-07 22:52:04.838 mutableArray[621:39737] mArray1 count: 0

Program ended with exit code: 0





你可能感兴趣的:(Obj-C学习之路)