简体   繁体   English

返回强制转换为ARC下CFStringRef的NSString * —如何摆脱分析器警告?

[英]returning an NSString* casted to CFStringRef under ARC — how to get rid of analyzer warning?

Here is my function: 这是我的功能:

CFStringRef nameWithType (someEnum type) {
  NSString* r;
  switch (type) {
    case type1:
      r=@"type1";
      break;
    case type2:
      r=@"type2";
      break;
    case type3:
      r=@"type3";
      break;
  }
  return (__bridge CFStringRef)r;  // analyzer warns: Address of stack memory associated with local variable 'r' returned to caller.
}

This will get rid of the very hard to eliminate analyzer warning. 这将消除很难消除的分析仪警告。

CFStringRef nameWithType2(someEnum type){
    CFStringRef string = NULL;
    switch (type) {
        case type1:
            string = (__bridge CFStringRef)@"type1";
            break;
        case type2:
            string = (__bridge CFStringRef)@"type2";
            break;
        case type3:
            string = (__bridge CFStringRef)@"type3";
            break;
    }
    return string;
}

Just remember to not let this memory leak. 请记住不要让此内存泄漏。

Actually there is the "traditional way" (from the time before there was NSObject) to not not use NSString literals, but instead work with the CFSTR macro like so: 实际上,存在一种“传统方式”(从出现NSObject之前的时间开始),不使用NSString文字,而是使用CFSTR宏,如下所示:

CFStringRef nameWithType2(someEnum type){
    CFStringRef string = NULL;
    switch (type) {
        case type1:
            string = CFSTR("type1");
            break;
        case type2:
            string = CFSTR("type2");
            break;
        case type3:
            string = CFSTR("type3");
            break;
    }
    return string;
}

CFSTR(c_string) is the shortest method to create a CFStringRef and much shorter than (__bridge CFStringRef)@"NSString" CFSTR(c_string)是创建CFStringRef的最短方法,比(__bridge CFStringRef)@"NSString"短得多。

Also if somebody sees this code you get higher geek cred for knowing CFSTR. 另外,如果有人看到此代码,您也会因了解CFSTR而获得较高的信誉。 It smells of N00B to create an NSString literal, then convert that into a CFStringRef AND needing to add ARC memory management ownership transferance tags.... versus creating a CFStringRef right away. 创建NSString文字,然后将其转换为CFStringRef并需要添加ARC内存管理所有权转让标签...,有点像N00B。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM