Search code examples
iosobjective-cxmlnsdata

How to convert NSData variable into NSInteger variable in iOS


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

Solution

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