Objective-C insertObject:atIndex 和 arrayWithCapacity:

本文通过一份包含错误的Objective-C代码示例,介绍了NSMutableArray的基本使用方法及常见问题,特别是insertObject:atIndex:和arrayWithCapacity:方法的正确用法。

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

这份代码有几处错误?

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
        //
        [array insertObject:@"234" atIndex:0];
        //
        [array insertObject:@"234" atIndex:5];
        //
        [array replaceObjectAtIndex:7 withObject:@"123"];
    }
    return 0;
}
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
        //
        [array insertObject:@"234" atIndex:0];
        //错
        [array insertObject:@"234" atIndex:5];
        //错
        [array replaceObjectAtIndex:7 withObject:@"123"];
    }
    return 0;
}

为什么???
看看苹果怎么说
这里写图片描述

这里写图片描述

顺便提一下,arrayWithCapacity:这个方法主要是为了提高程序的运行速度.
这是我的独立博客
https://junyixie.github.io/2017/01/16/Objective-C-insertObject-atIndex-%E5%92%8C-arrayWithCapacity/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值