【问题标题】:Issue Converting NSString to Int将 NSString 转换为 Int 的问题
【发布时间】:2011-10-08 16:01:44
【问题描述】:

由于某种原因,当我将此 NSString 转换为整数时,我得到一个完全随机(但一致)的数字。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    // release the connection, and the data object
    [connection release];

    debtString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

    NSLog(@"String form: %@", debtString);
    [receivedData release];

    int debtInt = [debtString intValue];
    NSLog(@"Integer form: %i", debtInt);

}

这是我的控制台输出:

2011-07-19 11:43:18.319 National Debt[50675:207] Succeeded! Received 14 bytes of data
2011-07-19 11:43:18.320 National Debt[50675:207] String form: 14342943000000
2011-07-19 11:43:18.320 National Debt[50675:207] Integer form: 2147483647

如果我在NSLog(@"Integer form: %i", debtInt); 行上设置断点,并将鼠标悬停在上行中的debtString 值上,则摘要无效。我能想到的唯一原因是我在转换之前释放了debtString,但这显然不是真的。

【问题讨论】:

标签: objective-c nsstring integer


【解决方案1】:

您的字符串的 int 值高于 int 的最大值。因此它显示 int 的最大值为 2.147.483.647

【讨论】:

  • 尝试“long long”。 NSString 有 [debtString longLongValue]
  • int debtInt = [debtString longLongValue]; NSLog(@"Integer form: %lli", debtInt); 返回2011-07-19 12:31:52.396 National Debt[51367:207] String form: 14342943000000 2011-07-19 12:31:52.397 National Debt[51367:207] Integer form: 432424662392489408
  • @Peter - 您现在可以正确转换字符串,然后将其存储回一个 int,这对它来说太小了。试试 long long debtInt = [debtString longLongValue];而是。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-30
  • 2012-08-10
  • 2010-11-25
  • 2012-08-22
  • 1970-01-01
相关资源
最近更新 更多