首页 > 解决方案 > 带函数参数的 __strong 限定符有什么作用,特别是在 case function (const __strong NSString *const paths[])

问题描述

在 github 上的代码中发现了类似的行,我无法理解为什么需要 __strong,尤其是在 C 数组的上下文中。

编写了一个测试代码,无论是否使用 __strong 关键字,它似乎都运行相同。

#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <objc/message.h>

static unsigned long getRetainCount (id obj)
{
   SEL  s = NSSelectorFromString (@"retainCount");

   return (((NSUInteger (*)(id, SEL))objc_msgSend) (obj, s));
}
static NSArray *function (const __strong NSString *const paths[], int count)
{
   NSMutableArray  *anArray = [NSMutableArray array];
   
   if (count >= 2)  {
      NSLog (@"(fA) Retain for [1]: %lu", getRetainCount(paths[1]));
      
      [anArray addObject:paths[0]];
      [anArray addObject:paths[1]];

      NSLog (@"(fB) Retain for [1]: %lu", getRetainCount(paths[1]));
   }

   return (anArray);
}
int main (int argc, const char * argv[])
{
   @autoreleasepool {
      
      NSString  *otherPaths[2];
      NSArray   *myArray = nil;
      
      otherPaths[0] = @"Hello";
      otherPaths[1] = [NSString stringWithFormat:@"%@ - %s", @"World", "Again"];
  
      NSLog (@"(mA) Retain for [1]: %lu", getRetainCount(otherPaths[1]));
  
      myArray = function (otherPaths, 2);
  
      NSLog (@"(mB) Retain for [1]: %lu", getRetainCount(otherPaths[1]));
   }
   
   return 0;
}

输出是:

(mA) Retain for [1]: 3
(fA) Retain for [1]: 3
(fB) Retain for [1]: 4
(mB) Retain for [1]: 4

如果我将 otherPaths[0] 放在 NSLog() 中,它会保留 MAX_UINT 计数,因为它是静态字符串。

__strong 是否有任何使用方法或函数的参数?

标签: objective-cautomatic-ref-counting

解决方案


推荐阅读