简体   繁体   English

NSURLConnection initWithNibName吗?

[英]NSURLConnection in initWithNibName?

I dont know but since using iOS5 (now 5.1) and Xcode 4 (now 4.3) , ViewDidLoad gets called everytime no matter what. 我不知道,但是由于使用iOS5(现在为5.1)和Xcode 4(现在为4.3),因此无论何时都将调用ViewDidLoad。 I have to retrieve a JSON output from an API, but if I put the fetching code in ViewDidLoad, it gets called everytime. 我必须从API检索JSON输出,但是如果将获取的代码放在ViewDidLoad中,则每次都会调用它。 So my question is, is it OK/Legal(from Appstore perspective) to use the NSURLConnection code in initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ? 所以我的问题是,从initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil使用NSURLConnection代码是否可以(从Appstore的角度来看)?

Heres the code 继承人代码

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        jsonContent=[[NSMutableData alloc]init];
        stateConnection= [[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"MY API"]] delegate:self startImmediately:YES];
    }
    return self;
}

Edit: its not working. 编辑:它不起作用。 the NSURLConnection code doesnt work in this method. NSURLConnection代码在此方法中不起作用。 so what should i do so that it gets called only once? 所以我应该怎么做才能使其只被调用一次?

It's perfectly "legal" to put code in the init method as you describe. 将代码放入您所描述的init方法中是完全“合法”的。 Indeed, as you note, it's possible for viewDidLoad to be called multiple times (for example after a low memory warning). 确实,如您所述,有可能多次调用viewDidLoad (例如在内存不足警告之后)。

As for why your code isn't working, I don't think there's enough context to be sure. 至于为什么您的代码不起作用,我认为没有足够的上下文可以确定。 Is the code in the if block actually being executed? if块中的代码if实际执行? My guess is no. 我的猜测不是。 If you're using iOS5 and Storyboards, the initWithNibName method isn't used. 如果您使用的是iOS5和Storyboards,则不使用initWithNibName方法。 If you put the same code in an initWithCoding: method you might have more success. 如果将相同的代码放在initWithCoding:方法中,则可能会获得更大的成功。

Its perfectly fine to put that code into viewDidLoad . 将该代码放入viewDidLoad是完全可以的。 Just check, if you already initialised it. 只需检查一下是否已初始化即可。

if(jsonContent == nil) {
    jsonContent=[[NSMutableData alloc]init];
    stateConnection= [[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"MY API"]] delegate:self startImmediately:YES];
    }
}

With that check you could even start it later (if it fits your needs better, like in viewWillAppear' or viewDidAppear', or even after pressing a button or anything else. 有了该检查,您甚至可以稍后再启动它(如果它更适合您的需求,例如在viewWillAppear' or viewDidAppear'中,或者甚至在按下按钮或其他操作之后也可以)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM