基础语法(二)集合

本文详细介绍了Objective-C中几种主要的集合类,包括NSArray/NSMutableArray、NSDictionary/NSMutableDictionary、NSSet/NSMutableSet以及NSOrderedSet/NSMutableOrderedSet等的使用方法。通过实例展示了如何创建、初始化这些集合类,并进行基本的操作如添加、删除和修改元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1。NSArray / NSMutableArray:

NSArray *myArray = @[object1, object2, object3, 。。。];

__unused NSString *firstString = myArray[0];

p.s. __unused:宏(macro),声明一个对象但未使用时,compiler 不会报错

NSArray *immutableArray = @[object1, object2, object3, 。。。];

NSMutableArray *mutableArray = [ [ NSMutableArray alloc ]  initWithArray :  immutableArray ];  // 从不可变数组里初始化

[mutableArray  exchangeObjectAtIndex : 0  withObjectAtIndex:1 ] ;  //互换

[mutableArray  removeObjectAtIndex : 1 ] ;  //删除

[mutableArray  setObject : object1  atIndexedSubscript:0 ] ;  //设置

2。NSDictionary / NSMutableDictionary:

NSDictionary *immutableDic = @{ @"first":object1, @"second":object2, @"third":object3, 。。。};

NSString *first = immutableDic[ @"first"];

NSMutableDictionary *mutableDic = [ [ NSMutableDictionary alloc ]  initWithDictionary : immutableDic ] ;

mutableDic[@"first"] = objectN ;  //可变字典,在初始化后可以更改

3。NSSet / NSMutableSet  -无序集合,NSOrderedSet / NSMutableOrderedSet  -有序集合

NSSet *immutableSet = [ [ NSSet alloc ]  initWithObjects : object1, object2, object3, nil ] ;

NSMutableSet *mutableSet = [ NSMutableSet  setWithSet : immutableSet ] ;

[ mutableSet  addObject : object4 ] ;

[ mutableSet  removeObject : object3 ] ;

p.s.  当 对象被重复加入set时,set只会取一次


NSSet *setOfNumbers = [ NSSet setWithArray : @[ @3, @4, @1, @10, @9] ] ;  //无序打印,随机显示集合内的元素,即第0位不一定是3

NSOrderedSet *orderedSetOfNumbers = [ NSOrderedSet  orderedSetWithArray :  @[ @3, @4, @1, @10, @9] ] ;  //有序打印,按集合内的元素顺序显示


NSMutableOrderedSet  *mutableOrderedSet = [ NSMutableOrderedSet  orderedSetWithArray :  @[ @3, @4, @1, @10, @9] ] ;

[ mutableOrderedSet  removeObject : @3 ] ;

[ mutableOrderedSet  addObject : @0 ] ;  // 在末尾加 

[mutableOrderedSet  exchangeObjectAtIndex : 1  withObjectAtIndex : 2 ] ;

4。NSCountedSet  -可变,无序,集合内可以有重复对象,并可计算重复次数

NSCountedSet  *setOfNumbers =  [ NSCountedSet  setWithObjects : @10, @20, @10, @10, @30, nil ] ;

[ setOfNumbers  addObject :  @20 ] ;

[ setOfNumbers  removeObject: @10 ] ;

unsigned  long = [ setOfNumbers  countForObject : @10 ] ;   // %lu : 2



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值