Search code examples
objective-cself

can't access self?


In this function I get xml through a kiss xml function called AFKissXMLRequestOperation. But since it is void, I can't access the XMLDocument unless I NSLog it, but that isn't useful when I need to access the XML. So, I try to set it as a variable of self in order to access it in other functions. If I NSLog self.xmlDocument inside of the block, it works. But, when I NSLog it outside the block in the call NSLog(@"self!%@", [self.xmlDocument XMLStringWithOptions:DDXMLNodePrettyPrint]); it is NULL. So how can I access self.XMLDocument?

    -(id)xmlRequest:(NSString *)xmlurl
{
AFKissXMLRequestOperation* operation= [AFKissXMLRequestOperation XMLDocumentRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:xmlurl]] success:^(NSURLRequest *request, NSHTTPURLResponse *response, DDXMLDocument *XMLDocument) {
    NSLog(@"kiss operation %@", [XMLDocument XMLStringWithOptions:DDXMLNodePrettyPrint]);
    self.xmlDocument=XMLDocument;

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, DDXMLDocument *XMLDocument) {
    NSLog(@"Failure!");
}];

[operation start]; 
NSLog(@"self!%@", [self.xmlDocument XMLStringWithOptions:DDXMLNodePrettyPrint]);
return self.xmlDocument; 
}

Solution

  • NSURLRequest performs asynchroneously, so you will have to review either the way your code is organised, or using a synchroneous network operation.

    The error in your above code is that since NSURLRequest performs asynchroneously, the

    NSLog(@"self!%@", [self.xmlDocument XMLStringWithOptions:DDXMLNodePrettyPrint]);
    return self.xmlDocument; 
    

    is performed before the operation has finished, thus returning nil.

    Do you really need to return xmlDocument ? I don't think so, because you set it as a property. My guess is that in the success block, (where you set self.xmlDocument=XMLDocument; ) you could actually process the xmlDocument as you want to or call a method that do such.

    Hope that helps