如何用Objective-C将同一个函数的两个返回值显示为两个标签



我是Objective-C的新手。我写了一个返回两个值的函数。现在我想把它打印成两个单独的标签,我该怎么做?

-(NSString *)abc:(NSInteger)weeks year:(NSInteger)year{
............
return ca , da ;
}

当我像

这样调用这个函数时
resultLabel1.text = [self abc year:year];  //output show the value of da

现在我想把ca的值显示到resultLabel1中。文本和数据转换为resultLabel2.text

是可能的吗?

您只能从C和C派生语言中的任何方法返回单个值。因此,您只需要返回一个代表两个值的值。你可以通过使用NSDictionary实现这一点。

所以让它:

-(NSDictionary *)abc:(NSInteger)weeks year:(NSInteger)year{
     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
           ca, @"object1", 
           da, @"object2", nil];
    return dict;
}
另一种方法是返回NSArray:
- (NSArray *)abc:(NSInteger)weeks year:(NSInteger)year {
     NSArray *myArray = [NSArray arrayWithObjects:da, ca, nil];
     return myArray;
}

然后你可以使用这些值:

NSArray *myArray = [self abc:2 year:2004];
textLabel.text = (NSString *)[myArray objectAtIndex:0];
textLabel2.text = (NSString *)[myArray objectAtIndex:1];

正如Jules指出的那样,一个方法只能"返回"一个值。但是,您有几个选项可以返回多个值:

  1. 返回指向对象的指针,该对象包含多个值。对象可以是NSArray, NSDictionary或者你自己的类。朱尔斯的回答给出了一些例子。

  2. 在参数中传递多个指针,方法可以将结果存储在指向的对象或变量中。

  3. 返回一个有多个字段的结构体。这里有一个例子

我会使用NSDictionary从一个方法返回多个值。在字典中,每个值由键命名和引用。本例中的键为"ca"one_answers"da",值均为短文本字符串。

-(NSDictionary *) abc: (NSInteger) weeks year:(NSInteger) year {
   NSString* ca = [NSString stringWithFormat:@"Week is %d", weeks];
   NSString* da = [NSString stringWithFormat:@"Year is %d", year];
   return [[NSDictionary alloc] initWithObjectsAndKeys:ca, @"ca", da, @"da", nil];
}

调用该方法并使用如下代码挑选返回值:

   NSInteger weekParam = @"52".integerValue;
   NSInteger yearParam = @"2011".integerValue;
   NSDictionary *result = [self abc:weekParam  year:yearParam];
   NSLog(@"ca has value: %@", [result objectForKey:@"ca"]);
   NSLog(@"da has value: %@", [result objectForKey:@"da"]);

您的日志应该添加以下行:

ca has value: Week is 52
da has value: Year is 2011

你可以在一个块中"返回"多个对象作为参数:

- (void)method {
    [self returnMultipleObjectsWithCompletion:^(NSString *firstString, NSString *secondString) {
        NSLog(@"%@ %@", firstString, secondString);
    }];
}
- (void)returnMultipleObjectsWithCompletion:(void (^)(NSString *firstString, NSString *secondString))completion {
    if (completion) {
        completion(@"firstReturnString", @"secondReturnString");
    }
}

你必须返回一个带有这两个值的NSArray或NSDictionary。

最新更新