[英]Objective C - SecItemAdd has error:EXC_BAD_ACCESS (first time) and errSecDuplicateItem (second time)
[英]Objective C Integer is 0 first time, but it changes second time
好的,所以我有这个程序可以通过Web服务器进行通信(PHP脚本)
我有这种方法,我想获得一个表的随机ID。 该NSURLconnection的返回数据被假定为表中的行数。
第一次调用它,它的像randomid变量没有被设置,但是第二次我运行它,它被设置了。
变量设置:
@implementation ViewController {
NSMutableData *randomData;
int randomid;
}
这是我的按钮操作:
- (IBAction)initVits:(id)sender {
[self randomID];
NSLog(@"Random ID: %d", randomid);
}
第一次输出是:随机ID:0,第二次:随机ID:有效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];
}
连接确实完成加载:
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;
}
输出始终为:返回:(表中的行数)temp:(表中的int的行数)随机数:(随机数)
就像第一次没有设置randomid变量一样。
谢谢你的时间!
[self randomID]立即返回,因为您正在randomID函数内进行异步调用。
在NSLog ivar randomid之后执行的didFinish回调上设置了randomid。
您正在使用异步网络,因此在从服务器检索随机ID之前将调用NSLog
。 有多种解决方案。
connectionDidFinishLoading
方法末尾生成ID时,放入NSLog
语句或您要执行的操作 您添加了吗?
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[randomData appendData:data];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.