5

我在求和两个 NSInteger 时遇到问题,我尝试使用简单的 int 但找不到答案。我的头文件中有这个:

@interface ViewController : UIViewController {
NSMutableArray *welcomePhotos;
NSInteger *photoCount;        // <- this is the number with the problem
//static int photoCount = 1;
}

在我的实施领域,我有:

-(void)viewDidLoad{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    photoCount = 0;
    welcomePhotos = [NSMutableArray array];


    int sum = photoCount + 1;

    NSLog(@"0 + 1 = %i", sum);

}

las NSLog 总是打印0 + 1 = 4

另外,如果这样做:

if (photoCount < [welcomePhotos count]){
    photoCount++;
    NSLog(@"%i", photoCount);
}else{
    photoCount = 0;
}

几次我得到:4, 8, 12

所以它跳过了四个,但我无法理解为什么。

4

3 回答 3

5

您将photoCount实例 var声明为指向NSInteger. 但是 NSInteger 是一个标量类型。
删除 .h 文件中的星号,然后重试。

代替

NSInteger *photoCount; 

NSInteger photoCount; 
于 2013-01-21T18:08:26.450 回答
3

你用指针指向NSInteger...

将其更改为NSInteger photoCount;

NSInteger 只是一个 int,您将它视为一个包装器对象。不需要指针。

于 2013-01-21T18:07:34.523 回答
3

您正在打印出一个指针对象,我相信您已将其声明为

NSInteger* photocount;

尝试将其更改为

int photocount;

在整数上做一个变量++会增加一个指针的大小,在 iOS 上它是 4 个字节。

于 2013-01-21T18:07:41.060 回答