new to the Objective-C/iOS scene. Experienced in PHP and C++.
I’m having a little trouble using NSInvocationOperation. Here’s my situation:
With some help online, I’ve a class, getData.h where getData.m contains:
#import "getData.h"
@implementation getData
@synthesize allData;
-(void)loadData{
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(getXML) object:nil];
[queue addOperation:operation];
[operation release];
}
-(void)getXML{
NSURL *url = [NSURL URLWithString:@"http://tubeupdates.com/rss/all.xml"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
if (response == nil) {
// Check for problems
if (requestError != nil) {
NSLog(@"Error!");
}
}
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (allData)
[allData appendData:data];
else
allData = [[NSMutableData alloc] initWithData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullName = [NSString stringWithFormat:@"feed.xml"];
NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@",docDir,fullName];
[allData writeToFile:fullFilePath atomically:YES];
}
-(void)dealloc{
[allData release];
[super dealloc];
}
@end
I know that the method is being called into the queue as I had made a temporary “printthis” method for it to call which simply displayed some text with NSLog. However my issue arises when trying to call the getXML function (to copy the XML file from the server). getXML works if I call it directly, but doesn’t when I add it to the Queue. It’s very likely that I’m missing the bigger picture and that I haven’t fully understood everything before I’ve started. I would appreciate some help on this. It seems no matter how good you are at C++, PHP etc, iOS Programming is a tough one!
In
getXMLyou are doing a synchronous request, meaning that when the method returns, the entire data for the the request will be in yourresponseNSData variable. Instead of waiting for the connection to finish loading with the delegate method, thesendSynchronousRequestblocks and returns when the request is finished. Likewise yourdidReceiveDatadelegate method will never get called.So to solve your problem, simply take your completion logic that is in the
connectionDidFinishLoadingmethod currently, and move it to thegetXMLmethod after the synchronous call returns.