【问题标题】:string with format as argument for method (objective-c)以格式作为方法参数的字符串(objective-c)
【发布时间】:2010-11-05 18:26:41
【问题描述】:

[NSString stringWithFormat:]; 可以接受多个参数,即使它被声明为 NSString 而不是 NSArray 并且只有一个冒号。

我怎样才能为我自己的方法使用它,这就像 NSLog 的替代品,它写入一个文本字段,所以它经常被使用,我不想继续添加更多的方括号。

【问题讨论】:

    标签: objective-c macos nsstring


    【解决方案1】:

    在参数名称后使用省略号:

     (NSNumber *) addValues:(int) count, ...;
    

    http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocDefiningClasses.html

    然后您需要使用va_listva_start 来遍历提供的参数:

    - (NSNumber *) addValues:(int) count, ...
    {
      va_list args;
      va_start(args, count);
    
      NSNumber *value;
    
      double retval;
    
      for( int i = 0; i < count; i++ )
      {
        value = va_arg(args, NSNumber *);
    
        retval += [value doubleValue];
    
      }
    
      va_end(args);
      return [NSNumber numberWithDouble:retval];
    }
    

    示例来自:http://numbergrinder.com/node/35

    请注意,这是一个内置的 C 功能,而不是 Objective-C 的一部分;这里对 va_arg 的用法有很好的解释:

    http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html

    【讨论】:

    • 我将如何使用 stringWithFormat 执行此操作?说我想要一个名为titleWithFormat:的方法
    • 你的方法签名应该是 -(NSString *) titleWithFormat:(NSString *)format, ...;
    • 我的第二个链接提供了使用 while 循环而不是 for 循环的示例,您可以使用它来遍历提供的每个参数。如果您想要的内容与 stringWithFormat 相同;您应该能够调用该方法并传递参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 2012-06-25
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多