2013-01-21 65 views
5

我有一个问题,总结两个NSInteger,我尝试过简单的int但无法找到答案。我有这个在我的头文件:总结两个NSInteger给出不正确的结果

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

的对我实施FIEL我:

-(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); 

} 

拉斯维加斯的NSLog始终打印0 + 1 = 4

而且如果要是做:

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

我几次得到:4,8,12

因此,它正在滑行四,但我不明白为什么。

+2

的问题是,你声明'photoCount'是一个指向'NSInteger'。请记住,'NSInteger'是一个有符号整数的typedef(取决于系统的32位或64位)。 –

+0

也许是因为NSInteger是一个特殊的int,它根据平台的位数(32位或64位)在运行时取不同的值。 –

回答

3

你打印出一个指针对象,我相信你已经声明它作为

NSInteger* photocount; 

尝试将其更改为

int photocount; 

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

+1

为什么不是'NSInteger photocount;'? – vikingosegundo

3

您使用指针NSInteger ...

将其更改为NSInteger photoCount;

NSInteger的只是一个int,而你把它当作一个包装对象。指针不需要。

+0

谢谢,就是这样,我需要学习更多obj-c –

5

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

更换

NSInteger *photoCount; 

NSInteger photoCount; 
+1

最佳答案但迟到一分钟;) –