首页 > 代码库 > NSMutableArray--可变数组
NSMutableArray--可变数组
// // 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; }
NSMutableArray--可变数组
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。