卡在这个 while 循环中
为什么我的 loginAuth
卡在 while 循环中?
我将 connectionFinishLoading
声明为
@interface LoginViewController : UIViewController {
BOOL connectionFinishLoading;
}
@property (nonatomic, assign) BOOL connectionFinishLoading;
@implementation LoginViewController
@synthesize connectionFinishLoading;
-(BOOL)loginAuth {
NSString *requestString = [NSString stringWithFormat:@"http:myURL?id=%@&format=JSON", userName.text];
NSMutableURLRequest *requestURL = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestString]];
loginConnection = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES];
[SVProgressHUD showInView:self.view status:@"Logging in"];
while (!connectionFinishLoading) {
NSLog(@"waiting..");
}
// code to executed after connection did finish loading.
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
connectionFinishLoading = YES;
}
Why is my loginAuth
stuck inside the while loop?
I declared connectionFinishLoading
as
@interface LoginViewController : UIViewController {
BOOL connectionFinishLoading;
}
@property (nonatomic, assign) BOOL connectionFinishLoading;
@implementation LoginViewController
@synthesize connectionFinishLoading;
-(BOOL)loginAuth {
NSString *requestString = [NSString stringWithFormat:@"http:myURL?id=%@&format=JSON", userName.text];
NSMutableURLRequest *requestURL = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestString]];
loginConnection = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES];
[SVProgressHUD showInView:self.view status:@"Logging in"];
while (!connectionFinishLoading) {
NSLog(@"waiting..");
}
// code to executed after connection did finish loading.
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
connectionFinishLoading = YES;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您阻塞了运行循环并且没有数据包通过网络发送,因此连接永远不会完成。
Because you block the run loop and no packets are send over the network, thus the connection never finishes.
尝试添加这个:
但是创建这样的循环是非常糟糕的做法
Try to add this:
But it is very bad practice to create such loops
正如 JustSid 提到的,运行循环被阻塞。我建议摆脱“while”循环和 BOOL connectionDidFinishLoading 属性,然后将要执行的代码移动到 connectionDidFinishLoading 方法中。您仍然应该以某种方式处理连接失败块。
As JustSid mentioned, the run loop is being blocked. I would suggest getting rid of the "while" loop and BOOL connectionDidFinishLoading property, and then move your code to be executed into the connectionDidFinishLoading method. You should still handle the connection failed block some way too.