【问题标题】:Questions about NSUinteger and int关于 NSUinteger 和 int 的问题
【发布时间】:2016-01-30 02:19:44
【问题描述】:

我使用 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++不会被执行。谁能告诉我为什么?

【问题讨论】:

    标签: objective-c int jsonmodel nsuinteger


    【解决方案1】:

    让我们看看这条线:

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

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

    NSUInteger,就像int 是一个标量 类型。与老式 C 一样,它只是内存中的一组字节,其值是这些字节的数值。一个对象,即使是一个表示数字的对象,比如NSNumber,也不能使用 c 风格的强制类型转换(此外,类型转换的优先级很低,这个表达式实际上只是转换了self,也很荒谬)。

    因此,self.campusBusArray 似乎是一个字典数组(可能是解析描述对象数组的 JSON 的结果)。您似乎希望这些字典有一个名为 [@"StationIndex"] 的键,并带有一个数值。 必须根据objective-c集合的规则是NSNumber(它们保存对象)。因此:

    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++;
        }
    }
    

    【讨论】:

    • 非常感谢!现在我发现我犯了这个错误,因为我忘记了字典中的值必须是一个对象,所以一个 NSUInteger 将被装箱到一个 NSNumber 中。再次感谢您!
    猜你喜欢
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2014-04-06
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多