简体   繁体   中英

Objective C Integer is 0 first time, but it changes second time

Okay so i have this program that is suposed to communicate over a Webserver(PHP Script)

I have this method that i want to get a random id for a table. The return data of this NSURLconnection is supose to be the amount of rows in the table.

First time i call it, its like randomid variables does not get set, but second time i run it, it does get set.

variable setting:

@implementation ViewController {
NSMutableData *randomData;
int randomid;
}

Here is my IBaction for a button:

- (IBAction)initVits:(id)sender {
[self randomID];
NSLog(@"Random ID: %d", randomid);    
}

The output first time is: Random ID: 0, second time: Random ID: a valid id

RandomID:

- (void) randomID {

NSString *url = @"http://ivitserdk.porkhost.dk/ivitserdk.php?function=randomid";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]   cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0];
connectionRandomID = [[NSURLConnection alloc] initWithRequest:request delegate:self];

randomData = [NSMutableData data];
[connectionRandomID start];
}

Connection did finish loading:

 if(connection == connectionRandomID) {
    NSString *String = [[NSString alloc] initWithData:randomData encoding:NSUTF8StringEncoding];
    NSLog(@"Return: %@", String);
    int temp = [String integerValue];
    NSLog(@"temp: %d", temp);
    randomid = (arc4random() % temp) + 1;
    NSLog(@"Random: %d", randomid);
    randomData = nil;
    connectionRandomID = nil;
 }

Output is for all times: Return: (number of rows in table) temp: (number of rows in table to a int) Random: (a random number)

Its like the randomid variable does not get set the first time.

Thanks for your time!

[self randomID] returns immediatly because you are doing an async call inside randomID function.

randomid is set on the didFinish callback that it is executed after you NSLog the ivar randomid.

You are using asynchronous networking, so your NSLog is called before the random ID is retrieved from the server. There are multiple solutions to this.

  • Use synchronous networking (I don't recommend this, so I don't go further into that)
  • Put the NSLog statement or whatever you want to do when the ID is generated at the end of your connectionDidFinishLoading method
  • If possible, I'd recommend generating the ID on the device (but I guess you need an unique key for a database, an URL or something, so this will probably not work for you)

Did you add this ?

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[randomData appendData:data];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM