您好,我正在使用基础工具使用 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]);
}
}
我的查询是,上面的代码在执行时显示给定的输出,但是一旦应用程序完成执行,我就会收到错误,提示“无法分配区域”,您可以帮忙吗?
另外,我想知道 icode 博客中 NSArray 和 NSMutable Array 之间的区别,我读到 nsarray 可以动态调整大小,所以如果 NSArray 可以动态调整大小,那么为什么要使用 NSMutable 数组,或者更好的一个是何时使用 NSArray 以及何时使用 NSMutable大批???
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]);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)