0

我使用 JSONModel 从 json 中捕获数据:

@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++不会执行。有人可以告诉我为什么吗?

4

1 回答 1

1

让我们看一下这一行:

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

%@表示将在日志中包含一个对象,该对象实现description. 这很好,因为表达式的结尾取消了对可能只包含对象的字典的引用。

NSUInteger, likeint标量类型。和老式的 C 一样,它只是内存中的一组字节,其值是这些字节的数值。一个对象,即使是一个表示数字的对象,NSNumber也不能使用 c 风格的强制转换(此外,强制转换的优先级很低,这个表达式真的只是强制转换self,也是无意义的)。

所以看起来这self.campusBusArray是一个字典数组(可能是解析描述对象数组的 JSON 的结果)。看来您希望这些字典有一个[@"StationIndex"]用数值调用的键。这必须符合NSNumberobjective-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++;
    }
}
于 2016-01-30T02:46:51.980 回答