【问题标题】:Can I view the implementation of the appendFormat instance method in Objective-C?我可以查看 Objective-C 中 appendFormat 实例方法的实现吗?
【发布时间】:2017-05-23 16:34:45
【问题描述】:

我想看看 appendFormat 在 Objective-C 中是如何实现的:

https://developer.apple.com/reference/foundation/nsmutablestring/1497308-appendformat

- (void)appendFormat:(NSString *)format, ...;

有没有办法查看实现?

我发现了这个:

https://github.com/cjwl/cocotron/blob/master/Foundation/NSString/NSMutableString.m#L111

-(void)appendFormat:(NSString *)format,... {
   NSString *string;
   NSRange   range={[self length],0};
   va_list   arguments;

   va_start(arguments,format);

   string=NSAutorelease(NSStringNewWithFormat(format,nil,arguments,NULL));
   va_end(arguments);

   [self replaceCharactersInRange:range withString:string];
}

但我不确定它是否与 Cocoa 相同。

我想查看实现,以便确认运行时。由于appendFormat 用于可变字符串,我假设appendFormat 的运行时间是最坏情况O(n) 和摊销O(1),但我不确定。

(我不是 Objective-C 开发人员。)

【问题讨论】:

    标签: objective-c cocoa


    【解决方案1】:

    您看不到 -[NSMutableString appendFormat:] 的源代码,因为它在 Apple 之外不可用。

    您可以反汇编 Foundation 框架来查看实现。我做了(使用 Hopper),实现基本上是这样的:

    - (void) appendFormat:(NSString *)format, ... {
        va_list ap;
        va_start(ap, format);
        NSString *string = [[NSString allocWithZone:nil] initWithFormat:format locale:nil arguments:ap];
        [self replaceCharactersInRange:NSMakeRange(self.length, 0) withString:string];
        va_end(ap);
    }
    

    如果你看一下initWithFormat:locale:arguments:的反汇编,你可以看到它调用了_CFStringCreateWithFormatAndArgumentsAux2。源代码(来自 macOS 10.10.5)在here 可用。最终你会发现自己在__CFStringAppendFormatCore,在同一个文件中。此函数解释格式字符串。

    您必须反汇编 CoreFoundation 才能找到 replaceCharactersInRange:withString: 的实现。它只是调用__CFStringCheckAndReplace,它在我上面链接的同一个CoreFoundation 源文件中定义。您可以从那里向下钻取,最终发现当 CoreFoundation 需要扩展为字符串分配的存储空间时,它每次都会扩展 3/2 倍。这是指数级增长,因此在replaceCharactersInRange:withString: 中花费的总时间为 O(n)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 2020-09-13
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多