ios developer tiny share-20161021

本文介绍了Objective-C中可变数组NSMutableArray的使用方法,包括如何添加、移除和替换元素,以及如何对数组进行就地排序。通过示例代码展示了NSMutableArray与NSArray的主要区别。

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

今天讲Objective-C的可变数组,之前讲的NSArray是不可变的,immutable,今天讲NSMutableArray,它是可变的。


Mutability

Although the NSArray class itself is immutable, this has no bearing on any collected objects. If you add a mutable string to an immutable array, for example, like this:

NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
NSArray *immutableArray = @[mutableString];

there’s nothing to stop you from mutating the string:

if ([immutableArray count] > 0) {
	id string = immutableArray[0];
	if ([string isKindOfClass:[NSMutableString class]]) {
		[string appendString:@" World!"];
	}
}

If you need to be able to add or remove objects from an array after initial creation, you’ll need to use NSMutableArray, which adds a variety of methods to add , remove or replace one or more objects:

NSMutableArray *mutableArray = [NSMutableArray array];
[mutableArray addObject:@"gamma"];
[mutableArray addObject:@"alpha"];
[mutableArray addObject:@"beta"];

[mutableArray replaceObjectAtIndex:0 withObject:@"epsilon"];

This example creates an array that ends up with the objects @"epsilon", @"alpha", @"beta".

It’s also possible to sort a mutable array in place, without creating a secondary array:

[mutableArray sortUsingSelector:@selector(caseInsensitiveCompare:)];

In this case the contained items will be sorted into the ascending, case insensitive order of @"alpha", @"beta", @"epsilon".
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值