-1

I have the following code that works. It successfully displays myName in the NSLog ...

NSURL *apiString = [NSURL URLWithString:@"http://testapi.com/url"];

[XMLConverter convertXMLURL:apiString completion:^(BOOL success, NSDictionary *dictionary, NSError *error)
{
    if (success)
    {
        NSString *myName = dictionary[@"profile"][@"real_name"];
        NSLog(@"%@ is my name", myName);
    }
}];

I have the following code for the method convertXMLURL which is in XMLConverter.m which I imported. It does a nice job of converting my XML to NSDictionary. That is what I want ...

+ (void)convertXMLURL:(NSURL *)url completion:(OutputBlock)completion
{
///Wrapper for -initWithContentsOfURL: method of NSXMLParser
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[[XMLConverter new] parser:parser completion:completion];
});
}

The problem I have is *dictionary is a local variable. I need to use it elsewhere in the code. How can I return it?

fpg1503
  • 7,492
  • 6
  • 29
  • 49
  • As for the answer below you can declare a Dictionary property either in the .h or .m file, depending on your visibility requirements. – carlodurso Jan 13 '15 at 02:16

1 Answers1

3

Simply create a @property and assign dictionary to it inside your completion handler.

For example:

Class Foo

@interface Foo : NSObject

@property (strong, nonatomic) NSDictionary* dictionary;

@end

Completion handler

NSURL *apiString = [NSURL URLWithString:@"http://testapi.com/url"];

[XMLConverter convertXMLURL:apiString completion:^(BOOL success, NSDictionary *dictionary, NSError *error)
{
    if (success)
    {
        NSString *myName = dictionary[@"profile"][@"real_name"];
        NSLog(@"%@ is my name", myName);
        myInstanceOfFoo.dictionary = dictionary;
    }
}];

EDIT: If the completion handler is not inside a member of the Foo class the dictionary property must be declared in the header file (.h). Otherwise you can declare it in the implementation file (.m).

Based on the comment by carlodurso

Community
  • 1
  • 1
fpg1503
  • 7,492
  • 6
  • 29
  • 49