gpt4 book ai didi

iphone - Objective C Integer 第一次为 0,但第二次发生变化

转载 作者:行者123 更新时间:2023-11-28 20:26:40 25 4
gpt4 key购买 nike

好吧,我有这个程序可以通过网络服务器(PHP 脚本)进行通信

我有这个方法,我想为一个表获取一个随机 ID。这个 NSURLconnection 的返回数据应该是表中的行数。

我第一次调用它时,它就像 randomid 变量没有被设置,但是我第二次运行它时,它确实被设置了。

变量设置:

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

这是我的一个按钮的 IBaction:

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

第一次输出是:Random ID: 0,第二次:Random ID: a valid id

随机ID:

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

连接完成加载:

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

所有时间的输出:返回:(表中的行数)临时:(表中的行数到一个整数)随机:(一个随机数)

好像 randomid 变量不是第一次设置。

感谢您的宝贵时间!

最佳答案

[自随机ID]立即返回,因为您正在 randomID 函数中进行异步调用。

randomid 是在 didFinish 回调上设置的,它是在你 NSLog the ivar randomid 之后执行的。

关于iphone - Objective C Integer 第一次为 0,但第二次发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13673356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com