【问题标题】:Objective C - How to return local variable in this code?Objective C - 如何在这段代码中返回局部变量?
【发布时间】:2015-03-10 22:09:14
【问题描述】:

我有以下有效的代码。它成功地在 NSLog 中显示 myName ...

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);
    }
}];

我在导入的 XMLConverter.m 中的方法 convertXMLURL 有以下代码。它很好地将我的 XML 转换为 NSDictionary。这就是我想要的……

+ (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];
});
}

我遇到的问题是 *dictionary 是一个局部变量。我需要在代码的其他地方使用它。怎么退货?

【问题讨论】:

  • 至于下面的答案,您可以在 .h 或 .m 文件中声明一个 Dictionary 属性,具体取决于您的可见性要求。
  • 不客气! :) 如果对你有帮助,你能接受吗?

标签: ios objective-c xcode methods local-variables


【解决方案1】:

只需创建一个@property 并将dictionary 在您的completion handler 中分配给它。

例如:

Foo 类

@interface Foo : NSObject

@property (strong, nonatomic) NSDictionary* dictionary;

@end

完成处理程序

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;
    }
}];

编辑:如果完成处理程序不在 Foo 类的成员中,则必须在头文件 (.h) 中声明 dictionary 属性。否则你可以在实现文件中声明它(.m)。

基于carlodurso的评论

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2013-10-03
    相关资源
    最近更新 更多