有没有办法强制您的应用程序处理其他事件?我有一个循环应该等待 10 秒以获得 json 响应。问题似乎是在 didReceiveData 事件可以运行之前循环处理。
JsonArray 是一个 NSArray 属性。
这是我在 Session.m 中的代码:
-(BOOL)logIn
{
JsonArray = nil;
if (([Password class] == [NSNull class]) || ([Password length] == 0))
return NO;
if (([Username class] == [NSNull class]) || ([Username length] == 0))
return NO;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL_ALL_PROPERTIES]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
if (!connection)
{
return NO;
}
int time = CFAbsoluteTimeGetCurrent();
while (!JsonArray)
{
if (CFAbsoluteTimeGetCurrent() - time == 10)
{
NSLog(@"breaking loop");
break;
}
// process events here
}
if (!JsonArray) return NO;
NSLog(@"JsonArray not nil");
return YES;
}
didReceiveData 处理程序:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"Data received");
NSError *e = nil;
JsonArray = nil;
JsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
if (!JsonArray)
{
JsonArray = nil;
Connected = NO;
return;
}
Connected = YES;
}
最佳答案
拥抱你正在尝试做的事情的异步性质。从 login
中删除返回方法并添加一个完成 block 。将完成 block 存储在属性中(副本)并从 connectionDidFinishLoading:
调用它.
typedef void (^MYCompletionHandler)(BOOL success);
@property (nonatomic, copy) void (^MYCompletionHandler)(bool *) completion;
- (void)loginUserWithCompletion:(MYCompletionHandler)completion {
self.completion = completion;
// start your login processing here
}
// when the login response is received
self. completion(##DID_IT_WORK##);
您当前的代码不起作用,因为在您的硬循环运行时主运行循环没有运行,因此委托(delegate)方法排队等待处理。不要尝试使用运行循环来解决它,正确处理异步性质。
关于objective-c - objective-c 在while循环中处理其他事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21737041/