标签:
// // main.m // OC04-task-08 // // Created by Xin the Great on 15-1-24. // Copyright (c) 2015年 Xin the Great. All rights reserved. // #import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... /////////////NSMutableArray--可变数组/////////// //使用了父类的构造方法构造一个可变数组 NSMutableArray *arr = [NSMutableArray array]; //NSMutableArray自己的构造方法,表示初始化数组的容量大小,注意:这里只是为了代码的可读性 NSMutableArray *arr0 = [NSMutableArray arrayWithCapacity:2]; //添加元素(对象) /* Inserts a given object at the end of the array. */ [arr0 addObject:@"1"]; [arr0 addObject:@"2"]; [arr0 addObject:@"3"]; NSLog(@"arr0 is %@",arr0); //用父类的方法构造 NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"1",@"3", nil]; NSLog(@"arr1 is %@",arr1); //向数组的末尾添加一个新元素 [arr addObject:@"x"]; NSLog(@"arr is %@", arr); //插入元素 [arr1 insertObject:@"2" atIndex:1]; [arr1 insertObject:@"0" atIndex:0]; NSLog(@"arr1 is %@",arr1); //删除元素 //删除最后一个元素 [arr1 removeLastObject]; NSLog(@"arr1 is %@",arr1); //删除指定下标元素 [arr1 removeObjectAtIndex:1]; NSLog(@"arr1 is %@",arr1); //删除指定元素 //如果元素不存在,则什么也不做 [arr1 removeObject:@"2"]; NSLog(@"arr1 is %@",arr1); //移除所有元素 [arr1 removeAllObjects]; NSLog(@"arr1 is %@",arr1); //添加多个元素 NSMutableArray *arr2 = [NSMutableArray arrayWithObjects:@"1",@"2", nil]; NSArray *lists = @[@"3",@"4",@"5",@"6"]; [arr2 addObjectsFromArray:lists]; NSLog(@"arr2 is %@",arr2); //替换和交换元素 //根据传进来的对象替换下标的目标对象 [arr2 replaceObjectAtIndex:2 withObject:@"7"]; NSLog(@"arr2 is %@",arr2); //根据两个元素的下标交换元素 [arr2 exchangeObjectAtIndex:2 withObjectAtIndex:5]; NSLog(@"arr2 is %@",arr2); //扩展: Person *ps = [[Person alloc] init]; ps.name = @"tom"; ps.age = 10; //数组的遍历 NSArray *arr3 = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",ps]; //传统遍历法 for (int i = 0; i < [arr3 count]; i++) { NSLog(@"arr3[%d] is %@",i, arr3[i]); } //快速遍历法 for (id value in arr3) { //循环块 if ([value isMemberOfClass:[Person class]]) { Person *ps = (Person *)value; NSLog(@"person name is %@",ps.name); continue; } NSLog(@"value is %@",value); } //mutableCopy NSArray *arr4 = @[@"1", @"2", @"3"]; NSLog(@"arr4 is %@", arr4); NSMutableArray *arr5 = [arr4 mutableCopy]; [arr5 addObject:@"4"]; NSLog(@"arr5 is %@", arr5); // NSMutableArray *arr6 = [NSMutableArray arrayWithArray:arr4]; } return 0; }
标签:
原文地址:http://blog.csdn.net/zuojx1013/article/details/43163627