Reputation: 6039
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!
Upvotes: 0
Views: 193
Reputation: 3772
In getXML
you are doing a synchronous request, meaning that when the method returns, the entire data for the the request will be in your response
NSData variable. Instead of waiting for the connection to finish loading with the delegate method, the sendSynchronousRequest
blocks and returns when the request is finished. Likewise your didReceiveData
delegate method will never get called.
So to solve your problem, simply take your completion logic that is in the connectionDidFinishLoading
method currently, and move it to the getXML
method after the synchronous call returns.
Upvotes: 2