2014-09-25 78 views
0

我使用以下方法检查我的用户数据消耗,取自here。它大部分时间都运行良好,但对于某些用户来说,它会返回负值。换句话说,WWANReceived是否定的。iPhone上的负值数据使用情况?

这怎么可能?有没有修复?

+ (NSArray *)getDataCounters { 

    BOOL success; 
    struct ifaddrs *addrs; 
    const struct ifaddrs *cursor; 
    const struct if_data *networkStatisc; 

    int WiFiSent = 0; 
    int WiFiReceived = 0; 
    int WWANSent = 0; 
    int WWANReceived = 0; 

    NSString *name = [[NSString alloc]init]; 

    // getifmaddrs 
    success = getifaddrs(&addrs) == 0; 
    if (success) 
    { 
     cursor = addrs; 
     while (cursor != NULL) 
    { 
     name = [NSString stringWithFormat:@"%s",cursor->ifa_name]; 
     // names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN 

     if (cursor->ifa_addr->sa_family == AF_LINK) 
     { 
      if ([name hasPrefix:@"en"]) 
      { 
       networkStatisc = (const struct if_data *) cursor->ifa_data; 
       WiFiSent += networkStatisc->ifi_obytes; 
       WiFiReceived += networkStatisc->ifi_ibytes; 
      } 

      if ([name hasPrefix:@"pdp_ip"]) 
      { 
       networkStatisc = (const struct if_data *) cursor->ifa_data; 
       WWANSent += networkStatisc->ifi_obytes; 
       WWANReceived += networkStatisc->ifi_ibytes; 
      } 
     } 

     cursor = cursor->ifa_next; 
     } 

     freeifaddrs(addrs); 
    } 

    return [NSArray arrayWithObjects:[NSNumber numberWithInt:WiFiSent], [NSNumber numberWithInt:WiFiReceived],[NSNumber numberWithInt:WWANSent],[NSNumber numberWithInt:WWANReceived], nil]; 
} 

回答

3

也许你已经解决了这个问题,我只是测试了相同的例子,并且发现了这个问题。

您必须将类型从int更改为long long来处理更大的值。你看到的是在2GB流量之后发生的整数溢出。

+0

谢谢@ jab11,我会给它一个镜头。 – Eddy 2014-11-17 10:31:25

+0

从堆栈溢出的肠子中复活... 哪些变量你必须从int变为long long,并且它有效吗?如果是的话,你应该接受答案! – Amos 2015-04-29 03:21:22

+0

@Amos里面的所有四个int变量都应该是long long类型的。同时返回的NSNumber应该用numberWithLongLong:calls创建。 – jab11 2015-04-30 10:18:21