如何在 iOS 中将 NSData 变量转换为 NSInteger 变量 [英] How to convert NSData variable into NSInteger variable in iOS

查看:40
本文介绍了如何在 iOS 中将 NSData 变量转换为 NSInteger 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following api method which returns NSData. I have called this method in another view controller. How to convert the NSData to 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];
}

推荐答案

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

Well, if you know that your data is really representing a single integer, the simplest way is the following:

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

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

UPD: NSInteger is defined depending on the architecture of the target processor and is either int or long. Feel free to replace int by NSInteger in the code above.

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

I'm also not sure that your data is an actual number and not it's string representation. In this case use something like

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

这篇关于如何在 iOS 中将 NSData 变量转换为 NSInteger 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆