简体   繁体   中英

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:

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"

Also if somebody sees this code you get higher geek cred for knowing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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