如何在Objective C中使用完成块来区分函数的返回值?

How to differentiate the returned value of a function using completion block in Objective C?

我有一个函数可以给出 2 个不同的字符串值,它们是 returned :

-(NSString*)load:(NSDictionary *)dict
{

    NSDictionary *dataDict = [self objectForId:@"data" fromDict:dict withDefault:nil];
    if (dataDict) {
        NSDictionary *success = [self objectForId:@"success" fromDict:dataDict withDefault:nil];

        NSString *str = [NSString stringWithFormat:@"%@", success];

        if ([str isEqualToString: @"1"])
        {
            NSDictionary *idDict = [self objectForId:@"id" fromDict:dataDict withDefault:nil];
            if (idDict) {
                NSString *idString = [NSString stringWithFormat:@"%@", idDict];
                return idString;
            }

        } else {
            NSDictionary *messages = [self objectForId:@"messages" fromDict:dataDict withDefault:nil];
            if (messages) {
                NSDictionary *messageDict = (NSDictionary *)messages;
                NSArray *type = messageDict[@"type"];
                if (type.count > 0) {
                    NSString *messageString = type[0][@"message"];
                    return messageString;
                }
            }
        }
    }
    return  nil;
}

并像这样访问字符串值:

 NSString *string = [className load:dict];

现在我想为 "idString" 和 "messageString" return 值编写 if else 语句。如何区分 2 个 return 值?

我的理解是您想知道加载方法 return 是 idString 还是 messageString。

所以我推荐的是使用一个棘手的方法。

您可以 return 类似

的字典,而不是 return 字符串
    return @{
         @"type":@"idString",
         @"content":idString
         }

并使用

NSDictionary * returnDict = [className load:dict]
if ([returnDict[@"type"] isEqualToString:@"idString"]) {
    //code here
}
else{
    //code here
}

最后,我知道这不是最佳解决方案,但它会很好用。

您可以使用 NSException。抛出 NSException

而不是返回 idString
@throw [NSException exceptionWithName:idString reason:nil userInfo:nil];

然后你可以这样调用你的方法:

@try{
    NSString *messageString = [className load:dict];
    NSLog(@"Message String: %@", messageString);
}@catch (NSException *e){
    NSString * idString = e.name;
    NSLog(@"ID String: %@",idString);
}

我会制作两种不同的方法。第一个只会 return id 字符串,第二个会 return 一条消息。

这样你就可以做出这样的东西:

NSDictionary *dict = /* some code here */;
NSString *message = nil;
NSString *idString = [foo loadId:dict];
if (idString.length == 0) {
    message = [foo loadMessage:dict];
}

创建一个将被返回的对象,而不是返回一个简单的字符串:

@interface Result: NSObject
@property (nonatomic) NSString *id;
@property (nonatomic) NSString *message;
@end

理想情况下,您可以创建 -initWithDictionary: 初始化程序来处理解析。

虽然返回 NSDictionary(参见 ), or a custom Class (see ),因为它是有效的解决方案,但可能太多了。
您需要记住返回的字典的键,或者可能为此创建自定义 class 太多了。

这里有另外两种可能性:

我将有示例字典来测试:

NSDictionary *dictToTest1 = @{@"id": @"idString",
                              @"noiseKey": @"noiseValue"
                              };
NSDictionary *dictToTest2 = @{@"messages": @"messagesString",
                              @"noiseKey": @"noiseValue"
                              };

我将简化您的测试,仅检查键 idmessages.

是否存在 key/value

使用双指针:

-(void)loadDict:(NSDictionary *)dict withRetKey:(NSString **)key andRetValue:(NSString **)value
{
    NSString *retKey = nil;
    NSString *retValue = nil;
    if (dict[@"id"])
    {
        retKey = @"id";
        retValue = dict[@"id"];
    }
    else if (dict[@"messages"])
    {
        retKey = @"messages";
        retValue = dict[@"messages"];
    }

    if (key)
    {
        *key = retKey;
    }

    if (value)
    {
        *value = retValue;
    }
}

样本测试:

NSString *key1 = nil;
NSString *value1 = nil;
[self loadDict:dictToTest1 withRetKey:&key1 andRetValue:&value1];
NSLog(@"Key1: %@\t value1: %@", key1, value1);
NSString *key2 = nil;
NSString *value2 = nil;
[self loadDict:dictToTest2 withRetKey:&key2 andRetValue:&value2];
NSLog(@"Key2: %@\t value2: %@", key2, value2);

输出:

$> Key1: id  value1: idString
$> Key2: messages    value2: messagesString

您在哪里看到对象的 &
几乎所有的时间都在管理一个NSError。 (linked question)
对于原始?例如,如果您想检索 UIColor (linked question)

的 red/blue/green/alpha

有方块:

-(void)blockLoadDict:(NSDictionary *)dict withBlock:(void(^) (NSString *key, NSString *value))block
{
    NSString *retKey = @"";
    NSString *retValue = @"";
    if (dict[@"id"])
    {
        retKey = @"id";
        retValue = dict[@"id"];
    }
    else if (dict[@"messages"])
    {
        retKey = @"messages";
        retValue = dict[@"messages"];
    }

    if (block)
    {
        block(retKey, retValue);
    }
}

样本:

__block NSString *key3 = nil;
__block NSString *value3 = nil;
[self blockLoadDict:dictToTest1 withBlock:^(NSString *key, NSString *value) {
    key3 = key;
    value3 = value;
}];
NSLog(@"Block Key3: %@\t value3: %@", key3, value3);

__block NSString *key4 = nil;
__block NSString *value4 = nil;
[self blockLoadDict:dictToTest2 withBlock:^(NSString *key, NSString *value) {
    key4 = key;
    value4 = value;
}];
NSLog(@"Block Key4: %@\t value4: %@", key4, value4);

输出:

$> Block Key3: id    value3: idString
$> Block Key4: messages  value4: messagesString