我有一個int currentFontSize,我想與存儲在C數組中的NSString比較,這裏是代碼。int stringWithFormat到NSString返回值
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
static NSString* fontSizeName[] =
{
@"14",
@"18",
@"22",
@"26",
@"30",
@"34",
};
int fontSizeSegmentID;
int currentFontSize = 22;
NSString *val = [NSString stringWithFormat: @"%i", currentFontSize];
NSString *val2 = @"22";
NSLog(@"the current font size is %i", currentFontSize);
NSLog(@"the current font Value1 is %i", val);
NSLog(@"the current font Value2 is %i",val2);
int i;
for (i = 0; i < 6; i++) {
NSLog(@"fontSizeNAme:%d",fontSizeName[i]);
NSLog(@"val:%d",val);
if (fontSizeName[i] == val) {
NSLog(@"They are equal");
fontSizeSegmentID = i;
break;
}
NSLog(@"the fontSizeSegmentID is: %i" , fontSizeSegmentID);
}
[pool drain];
return 0;
}
橫幅部分是,val給我返回值1879919632,這使我的比較失敗。奇怪的部分是,當我硬編碼的NSString作爲VAL2 = @「22」,比較成爲成功的地方VAL2是:4240,這是一樣的:
NSLog(@"fontSizeNAme:%d",fontSizeName[i]);
這裏是我的NSLog回報:
2010-11-18 16:56:52.784 testINT[26034:a0f] the current font size is 22
2010-11-18 16:56:52.786 testINT[26034:a0f] the current font Value1 is 1879919632
2010-11-18 16:56:52.787 testINT[26034:a0f] the current font Value2 is 4240
2010-11-18 16:56:52.788 testINT[26034:a0f] fontSizeNAme:4176
2010-11-18 16:56:52.788 testINT[26034:a0f] val:1879919632
2010-11-18 16:56:52.788 testINT[26034:a0f] the fontSizeSegmentID is: 32767
2010-11-18 16:56:52.789 testINT[26034:a0f] fontSizeNAme:4208
2010-11-18 16:56:52.789 testINT[26034:a0f] val:1879919632
2010-11-18 16:56:52.790 testINT[26034:a0f] the fontSizeSegmentID is: 32767
2010-11-18 16:56:52.790 testINT[26034:a0f] fontSizeNAme:4240
2010-11-18 16:56:52.790 testINT[26034:a0f] val:1879919632
2010-11-18 16:56:52.791 testINT[26034:a0f] the fontSizeSegmentID is: 32767
2010-11-18 16:56:52.791 testINT[26034:a0f] fontSizeNAme:4272
2010-11-18 16:56:52.791 testINT[26034:a0f] val:1879919632
2010-11-18 16:56:52.792 testINT[26034:a0f] the fontSizeSegmentID is: 32767
2010-11-18 16:56:52.792 testINT[26034:a0f] fontSizeNAme:4304
2010-11-18 16:56:52.792 testINT[26034:a0f] val:1879919632
2010-11-18 16:56:52.793 testINT[26034:a0f] the fontSizeSegmentID is: 32767
2010-11-18 16:56:52.793 testINT[26034:a0f] fontSizeNAme:4336
2010-11-18 16:56:52.794 testINT[26034:a0f] val:1879919632
2010-11-18 16:56:52.794 testINT[26034:a0f] the fontSizeSegmentID is: 32767
任何人都可以善意解釋我爲什麼?爲什麼我投了@「22」NString和一個形式的int返回一個不同的值?????謝謝!
實際上,程序會在'int'和指向Obj-C對象的指針之間進行比較,這是完全有效的,它只會給你非感性的結果。 – 2010-11-18 11:48:37
我相信這就是我所說的。 – 2010-11-18 12:08:19
@邁克爾艾金斯:無論你相信什麼,這不是你所說的。你說過:「你可能最終會遇到一個運行在系統緩衝區中的野號......或者超出範圍的異常」。如果你比較一個指向int的指針,那麼這兩者都不會發生。 – JeremyP 2010-11-18 14:48:56