[英]Objective-C JSON Parse don't work in other classes
我對NSURLConnectionDataDelegate有一個奇怪的問題。 我創建了一個用於解析json的類。 這里的代碼:
- (void)createJSONDictionaryFromURL:(NSURL *)url
{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
jsonData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[jsonData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Fail with error");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(@"%@", self.jsonDictionary);
}
在方法connectionDidFinishLoading中,一切都正確,控制台顯示正確的數據。 但是我想在ViewController的viewDidLoad方法中使用它。
JSONParser *parser = [[JSONParser alloc] init];
NSDictionary *dict = [[NSDictionary alloc] init];
[parser createJSONDictionaryFromURL:url];
dict = parser.jsonDictionary;
NSLog(@"%@", dict);
控制台顯示(空),有人可以幫助我嗎?
對不起,我的英語不好
由於網絡連接,您的JSONParser
是異步的(它是異步的)。 因此,當您當前調用parser.jsonDictionary
您會看到數據尚未准備好。
您不希望在數據可用之前嘗試阻塞,而是應該設置一個回調以在數據准備就緒時將其發送到視圖控制器(以便您可以保存並更新UI)。
這可以通過將delegate
屬性添加到JSONParser
視圖控制器分配自己並實現一些回調方法來完成。 或者,使用更少的代碼, JSONParser
可以提供視圖控制器設置的block屬性,並在connectionDidFinishLoading:
調用該@property
(確保@property
使用(復制,非原子)`)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.