【问题标题】:How to convert NSData variable into NSInteger variable in iOS如何在 iOS 中将 NSData 变量转换为 NSInteger 变量
【发布时间】:2011-05-25 10:30:24
【问题描述】:

我有以下返回 NSData 的 api 方法。我在另一个视图控制器中调用了这个方法。如何将 NSData 转换为 NSInteger

-(NSData *)getBusXMLAtStop:(NSString*)stopnumber
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: 
                                    [NSURL URLWithString: [NSString stringWithFormat:@"http://www.google.com/ig/api?weather=,,,50500000,30500000",stopnumber]]];
    [request setHTTPMethod: @"GET"];
    dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        NSLog(@"%@",dataReply);
    return dataReply;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    api *ap = [[api alloc]init];
    NSData *str = [ap getBusXMLAtStop:@"1"];
    // Here is where I want to convert str into NSInteger type. How is this possible?
    NSLog(@"this is success %@",ap.dataReply);
    TWeatherParser *parser = [[TWeatherParser alloc]init];
    [parser getInitialiseWithData:ap.dataReply];
    [parser release];
    [ap release];
}

【问题讨论】:

    标签: ios objective-c xml nsdata


    【解决方案1】:

    好吧,如果您知道您的数据确实代表一个整数,那么最简单的方法如下:

    NSData *data = ...;
    int i;
    [data getBytes: &i length: sizeof(i)];
    

    UPD:NSInteger 是根据目标处理器的体系结构定义的,可以是intlong。随意将上面代码中的int 替换为NSInteger

    我也不确定您的数据是实际数字而不是字符串表示形式。在这种情况下,使用类似

    NSString *str = [[[NSString alloc] initWithData:data encoding:(encoding you need)] autorelease];
    NSInteger value = [str intValue];
    

    【讨论】:

    • 但是方法返回 NSData 所以我怀疑当我将它直接转换为 nsstring 变量时它是否不会产生任何问题。谢谢
    • 我已经写了你的代码 NSString *str = [NSString stringWithData:aData encoding: (encoding you need) ]; NSInteger 值 = [str intValue];但它警告我 NSString 可能无法响应 stringWithData
    【解决方案2】:

    您可以在 NSString 上找到一个名为 initWithData: 的便捷初始化程序。请查看documentation 了解更多信息。

    示例:

    NSString * s = [[NSString alloc]initWithData:data encoding: NSUTF8StringEncoding];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 2016-09-12
      • 2013-06-09
      • 2016-11-29
      相关资源
      最近更新 更多