2016-01-30 44 views
0

我用JSONModel從JSON捕獲數據:約NSUinteger問題和int

@interface BBTCampusBus : JSONModel 

@property (strong, nonatomic) NSString * Name; 
@property (assign, nonatomic) NSUInteger Latitude; 
@property (assign, nonatomic) NSUInteger Longitude; 
@property (nonatomic)   BOOL  Direction; 
@property (assign, nonatomic) NSUInteger Time; 
@property (nonatomic)   BOOL  Stop; 
@property (strong, nonatomic) NSString * Station; 
@property (assign, nonatomic) NSInteger StationIndex; 
@property (assign, nonatomic) NSUInteger Percent; 
@property (nonatomic)   BOOL  Fly; 

@end 

而且我有以下代碼:

for (int i = 0;i < [self.campusBusArray count];i++) 
{ 
    NSLog(@"index at nsuinteger - %@", (NSUInteger)self.campusBusArray[i][@"StationIndex"]); 
    NSLog(@"index - %lu", index); 
    if ([(NSUInteger)self.campusBusArray[i][[@"StationIndex"] ]== index) 
    { 
     numberOfBusesCurrentlyAtThisStation++; 
    } 
} 

其實StationIndex是1或2位整數。例如我有self.campusBusArray[i][@"StationIndex"] == 4,並且我有index == 4,那麼兩個NSLog都輸出4,但它不會跳入if塊,否則將不會執行numberOfBusesCurrentlyAtThisStation++。有人可以告訴我爲什麼嗎?

回答

1

讓我們看一下行:

NSLog(@"index at nsuinteger - %@", (NSUInteger)self.campusBusArray[i][@"StationIndex"]); 

%@說,對象將包括日誌,一個實現description英寸這很好,因爲表達式的結尾會將字典解引用,該字典可能只包含對象。

NSUInteger,像int標量類型。像老式的C一樣,它只是一組內存中的字節,其值是這些字節的數值。一個對象,即使是一個表示數字的對象,如NSNumber也不能使用c風格轉換進行轉換(此外,轉換的優先級較低,此表達式實際上只是投射self,也是無意義的)。

所以看起來self.campusBusArray是一個字典數組(可能是解析JSON描述對象數組的結果)。看來你期望這些字典有一個數字值爲[@"StationIndex"]的密鑰。那必須是一個NSNumber由規則的objective-c集合(他們持有對象)。因此:

NSDictionary *aCampusBusObject = self.campusBusArray[i];  // notice no cast 
NSNumber *stationIndex = aCampusBusObject[@"StationIndex"]; // this is an object 
NSUInteger stationIndexAsInteger = [stationIndex intValue]; // this is a simple, scalar integer 

if (stationIndexAsInteger == 4) { // this makes sense 
} 

if (stationIndex == 4) { // this makes no sense 
} 

即最後行測試的指針的一個對象(在存儲器中的地址)等於4上做標量算術,或蒙上上,或者在對象指針比較幾乎從不說得通。

重寫......

for (int i = 0;i < [self.campusBusArray count];i++) 
{ 
    NSDictionary *aCampusBusObject = self.campusBusArray[i]; 
    NSNumber *stationIndex = aCampusBusObject[@"StationIndex"]; 
    NSUInteger stationIndexAsInteger = [stationIndex intValue]; 

    NSLog(@"index at nsuinteger - %lu", stationIndexAsInteger); 
    NSLog(@"index - %lu", index); 
    if (stationIndexAsInteger == index) 
    { 
     numberOfBusesCurrentlyAtThisStation++; 
    } 
} 
+0

非常感謝!現在我發現我犯了這個錯誤,因爲我忘記了字典中的值必須是一個對象,所以一個NSUInteger將被裝箱到一個NSNumber中。再次感謝你! – Caesar