ARC不允许将'int'隐式转换为'NSArray *'

时间:2013-03-12 16:36:56

标签: ios nsarray nsnumber

我试图用整数填充我的数组。但是,对我来说有些奇怪的事情并不像我想的那么容易。以下是对所发生情况的描述。

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

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

//.m file

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

4 个答案:

答案 0 :(得分:6)

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

例如:

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

或者,有简写:

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

无论哪种方式,都要将数据退出:

int value = [[a objectAtIndex:0] intValue];

答案 1 :(得分:1)

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

在.h文件中:

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

NSMutableArray *storeDisk = [[NSMutableArray alloc] init];
[storeDisk addObject:virdLabel.text];

答案 2 :(得分:1)

看起来你有理解NSArrays的根本错误。我建议你阅读一些iOS教程来学习核心可可类的语法和用法。

以下一行:

NSArray storeDisk[10];

生成包含10个单元格的NSArray。

这也不会像未经编辑的问题那样有效:

NSArray* storeDisk[15];

这将只生成一个包含15个NSArray指针的数组。只有当你尝试创建一个包含15个NSArrays的数组时,这才有用(而且,在Objective-C中有更好的方法可以做到这一点)。

您必须阅读有关NSArray的信息并使用正确的语法来使用它。 除此之外,NSArray不是正确的选择,因为它是不可变的。如果要将对象添加到数组,则必须使用可变数组。其次,要插入一个整数,必须使用cocoa包装器来表示数字 - NSNumber。 NSArray只能保存对象。

为了生产一个包含20个细胞的NSArray,一种可能就是使用这个代码:

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

仍然,强烈建议您暂停并阅读some tutorialsdocumentation

编辑以反映已编辑的问题。

答案 3 :(得分:0)

您无法按原样将int添加到数组中。数组只能接受对象,因此可以使用(id)或任何其他目标c对象创建。 如果要将int添加到NSArray中,请使用...

[arrayObj addObject:[NSNumber numberWithInteger:0]];
[arrayObj addObject:[NSNumber numberWithInteger:1]];