【问题标题】:Objective-C passing parameters in void methodObjective-C在void方法中传递参数
【发布时间】:2014-03-09 20:24:03
【问题描述】:

调用 void 方法时如何传递参数?我知道您可以这样做:

-(void)viewDidLoad {
    [self callMethod];
}

-(void)callMethod {
     //stuff here
}

但是如何将参数(例如 NSString)传递给 callMethod 方法?

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    这是一个带有整数参数的示例。

    -(void)viewDidLoad {
        [self callMethodWithCount:10];
    }
    
    -(void)callMethodWithCount:(NSInteger)count {
         //stuff here
    }
    

    在objective-c 中,参数包含在方法名称中。您可以像这样添加多个参数:

    -(void)viewDidLoad {
        [self callMethodWithCount:10 animated:YES];
    }
    
    -(void)callMethodWithCount:(NSInteger)count animated:(BOOL)animate{
         //stuff here
    }
    

    您似乎误解了方法开头的 void 是什么意思。这是返回值。对于 void 方法,调用该方法不会返回任何内容。如果你想从你的方法中返回一个值,你可以这样做:

    -(void)viewDidLoad {
        int myInt = [self callMethodWithCount:10 animated:YES];
    }
    
    -(int)callMethodWithCount:(NSInteger)count animated:(BOOL)animate{
         return 10;
    }
    

    你定义你的方法返回一个int(在这个例子中它总是返回10。)然后你可以将一个整数设置为调用该方法返回的值。

    【讨论】:

    • 我有点困惑什么是问题?问题的标题是“在 void 方法中传递参数”,但这个答案是关于“在方法中传递参数”。
    • 我的问题很可能是措辞不当。这确实是我正在寻找的解决方案。 “无效方法”和“方法”有什么区别?我对 iOS 开发比较陌生,不熟悉术语。
    • 方法可以返回不同的类型,例如 int 或 BOOL。一个 void 方法什么都不返回
    • 感谢您的澄清。
    【解决方案2】:
    - (void)callMethod:(NSString *)string 
    {
    
    }
    

    string 是你的parameter,所以你会打电话给

    NSString *myString = @"your string here......";
    [self callMethod:myString];
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      • 2014-07-14
      • 2011-09-13
      • 2011-09-30
      相关资源
      最近更新 更多