0

我正在尝试用整数填充我的数组。然而,对我来说有些奇怪的是,这并不像我想的那样容易。以下是对所发生情况的描述。

代码的最后一行给了我错误。“不允许将 int 隐式转换为 NSArray”

//.h file
{
NSArray storeDisk[15];
}
property int virdCount;
property (nonatomic, strong)NSArray *storeDisk;

//.m file

virdCount+=virdCount;
storeDisk[0]=virdCount;
4

4 回答 4

6

如果要将整数放入 中NSArray,则需要使用NSNumber.

例如:

NSArray *a = [NSArray arrayWithObject:[NSNumber numberWithInt:virdCount]];

或者,有简写:

NSArray *a = @[@(virdCount)];

无论哪种方式,要恢复数据:

int value = [[a objectAtIndex:0] intValue];
于 2013-03-12T16:45:16.147 回答
1

It seems like you have a fundamental mistake of understanding NSArrays. I would suggest you read some iOS tutorials to learn the syntax and usage of core cocoa classes.

The following line:

NSArray storeDisk[10];

Does not produce an NSArray with 10 cells.

Neither will this work, as was in the unedited question:

NSArray* storeDisk[15];

That will simply produce an array of 15 NSArray pointers. That would be useful only if you tried creating an array of 15 NSArrays (and still, there would be better ways to do this in Objective-C).

You must read about NSArray and use the correct syntax to use it. Other than that, NSArray is not the right choice since it is immutable. If you want to add objects to the array, you must use a mutable array. Second, to insert an integer you must use the cocoa wrapper for numbers - NSNumber. NSArray can only hold objects.

In order to produce an NSArray with 20 cells, one possibility is using this code:

NSMutableArray* array = [NSMutableArray arrayWithCapacity:20];
[array insertObject:[NSNumber numberWithInt:virdCount] atIndex:10];

Still, I highly suggest that you take a pause and read some tutorials or documentation.

Edited to reflect edited question.

于 2013-03-12T16:47:29.287 回答
1

您应该通过以下方式创建一个数组:

在 .h 文件中:

{
    NSMutableArray *storeDisk;
}
property int virdCount;
property (nonatomic, strong)NSMutableArray *storeDisk;

NSMutableArray *storeDisk = [[NSMutableArray alloc] init];
[storeDisk addObject:virdLabel.text];
于 2013-03-12T16:40:02.673 回答
0

您不能按原样将 int 添加到数组中。数组只能接受对象,因此它是使用 (id) 或任何其他目标 c 对象创建的。如果您想将 int 添加到 NSArray 使用...

[arrayObj addObject:[NSNumber numberWithInteger:0]];
[arrayObj addObject:[NSNumber numberWithInteger:1]];
于 2014-10-16T16:56:56.760 回答