NSArray和NSMutable阵列之间的区别 [英] Difference between NSArray and NSMutable Array

查看:115
本文介绍了NSArray和NSMutable阵列之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

他正在使用基础工具来处理NSArrays,我编写了以下代码

hi am working with NSArrays using foundation tool and i have wrote the following code

    -(void)simplearrays
{
 NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];

 for(int i =0;i<3;i++)
 {
  scanf("%d",&arr[i]);
 }
 for(int j =0; j<3;j++)
 {
  printf("\n%d",arr[j]);
 }
}

我的查询是,上面的代码在执行时显示给定的输出,但是一旦应用程序执行完毕,我会收到一条错误消息,提示无法分配区域",请您帮忙.

My query is that the above code when executed shows the given output but the i get an error once the application finishes execution which says that "can't allocate region" can you please help.

我还想知道icode博客中NSArray和NSMutable Array之间的区别,我已经读到nsarray可以动态调整大小,因此,如果NSArray可以动态调整大小,那么为什么要使用NSMutable数组,或者更好的选择是何时使用NSArray以及何时使用使用NSMutable数组???

Also i wanted to know the difference between NSArray and NSMutable Array in icode blog i have read that nsarray can dynamically resize so if NSArray can dynamically resize then why to use NSMutable array or a better one would be when to use NSArray and when to use NSMutable Array???

推荐答案

可可数组不是C数组.它们是与Java向量和数组列表有些相似的容器对象.

Cocoa arrays are not C arrays. They are container objects with some similarities to Java vectors and array lists.

您不能使用C下标语法添加或检索对象,您需要向该对象发送消息.

You cannot add objects or retrieve them using the C subscript syntax, you need to send messages to the object.

-(void)simplearrays
{
    NSMutableArray *arr = [NSMutableArray array]; 
    // arrayWithCapacity: just gives a hint as to how big the array might become.  It always starts out as
    // size 0.

    for(int i =0;i<3;i++)
    {
        int input;
        scanf("%d",&input);
        [array addObject: [NSNumber numberWithInt: input]];
        // You can't add primitive C types to an NSMutableArray.  You need to box them
        // with an Objective-C object
    }
    for(int j =0; j<3;j++)
    {
       printf("\n%d", [[arr objectAtIndex: j] intValue]);
       // Similarly you need to unbox C types when you retrieve them
    }
    // An alternative to the above loop is to use fast enumeration.  This will be
    // faster because you effectively 'batch up' the accesses to the elements
    for (NSNumber* aNumber in arr)
    {
       printf("\n%d", [aNumber intValue]);
    }
}

这篇关于NSArray和NSMutable阵列之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆