How to convert NSData variable into NSInteger variable in iOS

主宰稳场 提交于 2020-01-05 11:49:10

问题


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

回答1:


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 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];



回答2:


You can find a convenience initialiser on NSString called initWithData:. Please check out the documentation for more info.

EXAMPLE:

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


来源:https://stackoverflow.com/questions/6123029/how-to-convert-nsdata-variable-into-nsinteger-variable-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!