NSArray和NSMutable Array之间的区别

Rad*_*dix 2 objective-c

您正在使用基础工具使用NSArrays,我已经编写了以下代码

    -(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]);
 }
}
Run Code Online (Sandbox Code Playgroud)

我的查询是上面的代码在执行时显示给定的输出,但是一旦应用程序完成执行,我得到一个错误,说"无法分配区域",请你帮忙.

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

Ahm*_*dal 6

NSArray和NSMutableArray是表示数组行为的Foundation类和数据类型.您可以在两个对象中存储任何非基本类型的对象.两者都保留它们存储的对象,并在删除对象或释放数组对象本身时释放对象.什么时候用哪个?好吧,如果您不太可能在数组中添加/删除对象,则应通过调用其中一个静态方法并指定要存储的对象来使用NSArray,即:

NSArray *colors = [NSArray arrayWithObjects:@"Red", @"Green", @"Blue", nil];
Run Code Online (Sandbox Code Playgroud)

如果您可能在创建对象后向对象添加/删除对象,则应使用NSMutableArray.您可以创建数组,无论是否指定要存储的初始对象,然后随时向/从阵列添加/删除对象,即:

NSMutableArray *colors = [[NSMutableArray alloc] init];
[colors addObject:@"Red"];
[colors addObject:@"Green"];
[colors addObject:@"Blue"];
[colors removeObjectAtIndex:0];
NSLog(@"Color: %@", [colors objectAtIndex:1]);
[colors release];
Run Code Online (Sandbox Code Playgroud)

请检查以获取更多信息:集合编程主题


Jer*_*myP 6

Cocoa数组不是C数组.它们是容器对象,与Java向量和数组列表有一些相似之处.

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

-(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]);
    }
}
Run Code Online (Sandbox Code Playgroud)