我在全局int变量中存储了分数。每次游戏结束时,我都希望将每个新分数添加到数组中。所以,代码看起来像这样:
@implementation MainScene{
NSInteger *_scorevalue;
NSMutableArray *_scores;
}
在didLoad方法中:
[[NSUserDefaults standardUserDefaults] setObject:_scores forKey:@"gameScores"];
_scorevalue的值在游戏中发生变化(当物体碰撞时,但无关紧要):
_scorevalue=_scorevalue + 10;
游戏结束时:
[_scores addObject:_scorevalue];
Xcode在这里显示了一个问题:“将非Objective-C指针类型int隐式转换为类型为id的参数”。
我尝试将_scorevalue类型更改为在实现中浮动(相同的结果)。但是当我使用NSNumber时,[_scores addObject:_scorevalue];
附近的问题消失了,新问题出现在_scorevalue=_scorevalue + 10;
附近:“指向接口NSNumber的指针算术,这不是这个架构和平台的常量大小”。
你能解释一下吗?如何解决这一切?!
编辑Rob的回答:
实施:
NSInteger _scorevalue;
游戏结束时:
NSNumber *_scoreNumber= [NSNumber numberWithInteger:@(_scorevalue)]; // Xcode shows warning:
// "Incompatible pointer to integer conversion sending NSNumber to parameter of type NSInteger(aka // int)"
[_scores addObject:_scoreNumber];
编辑:因为nburk节目更好(没有警告):
[_scores addObject:@(_scorevalue];)
答案 0 :(得分:2)
NSInteger *_scorevalue;
这是一个指向整数的指针。你的意思是只有一个整数。删除*
。
您也无法在NSMutableArray
中添加整数。您需要将其加入NSNumber
,例如@(_scorevalue)
。
请注意,这不是实现属性的好方法。使用@property
:
@interface MainScene ()
@property(nonatomic, readwrite, strong) NSMutableArray *scores;
@property(nonatomic, readwrite, assign) NSInteger score;
@end
养成通过其属性访问这些内容的习惯:self.scores
和self.score
。即使使用ARC,直接ivar访问在ObjC中也不是一个好主意。
答案 1 :(得分:0)
具体而言,您可以绕过错误将定义或实例变量更改为:
@implementation MainScene{
NSInteger _scorevalue;
NSMutableArray *_scores;
}
并将数组添加到:
[_scores addObject:@(_scorevalue];)
请注意,通过执行此操作,您将_scoreValue
作为NSNumber
类型的对象进行处理,因此当您检索它时,您需要在该对象上调用integerValue
,例如:< / p>
NSNumber *theScoreAsNumber = _scores[0];
NSInteger theScoreAsInteger = [theScoreAsNumber integerValue];