I dont know but since using iOS5 (now 5.1) and Xcode 4 (now 4.3) , ViewDidLoad gets called everytime no matter what. I have to retrieve a JSON output from an API, but if I put the fetching code in ViewDidLoad, it gets called everytime. So my question is, is it OK/Legal(from Appstore perspective) to use the NSURLConnection code in initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ?
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. 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. Indeed, as you note, it’s possible for
viewDidLoadto be called multiple times (for example after a low memory warning).As for why your code isn’t working, I don’t think there’s enough context to be sure. Is the code in the
ifblock actually being executed? My guess is no. If you’re using iOS5 and Storyboards, theinitWithNibNamemethod isn’t used. If you put the same code in aninitWithCoding:method you might have more success.