开发者

Objective-C memory management regarding code not using `release`

I have found a code which is used to escape html chars. I have a question about this code. as you can see it "alloc"s and does not "release" it. does it causes of memory leaks? must it be released?

  htmlEscapes = [[NSDictionary alloc] initWithObjectsAndKeys:
//        @"&", @"&",
     开发者_如何学C   @"&lt;", @"<",
        @"&gt;", @">",
        @"&#039;", @"'",
        @"&quot;", @"\"",        
        nil
        ];

whole class

#import "NSString+HTML.h"


@implementation NSString (HTMLExtensions)

static NSDictionary *htmlEscapes = nil;
static NSDictionary *htmlUnescapes = nil;

+ (NSDictionary *)htmlEscapes {
 if (!htmlEscapes) {
  htmlEscapes = [[NSDictionary alloc] initWithObjectsAndKeys:
//        @"&amp;", @"&",
        @"&lt;", @"<",
        @"&gt;", @">",
        @"&#039;", @"'",
        @"&quot;", @"\"",        
        nil
        ];
 }
 return htmlEscapes;
}

+ (NSDictionary *)htmlUnescapes {
 if (!htmlUnescapes) {
  htmlUnescapes = [[NSDictionary alloc] initWithObjectsAndKeys:
//       @"&", @"&amp;",
       @"<", @"&lt;", 
       @">", @"&gt;",
       @"'", @"&#039;",
       @"\"", @"&quot;",
       nil
       ];
 }
 return htmlEscapes;
}

static NSString *replaceAll(NSString *s, NSDictionary *replacements) {
 for (NSString *key in replacements) {
  NSString *replacement = [replacements objectForKey:key];
  s = [s stringByReplacingOccurrencesOfString:key withString:replacement];
 }
 return s;
}

- (NSString *)htmlEscapedString {
 return replaceAll(self, [[self class] htmlEscapes]);
}

- (NSString *)htmlUnescapedString {
 return replaceAll(self, [[self class] htmlUnescapes]);
}

@end


Apparently, only one instance of NSDictionary is created and it's purposefully stored and reused for the life time of the application. It's not considered a memory leak (at least not in a single threaded environment; of course, a potential race condition is possible for the if statement).


It's a common pattern for implementing a singleton in Objective-C. One instance of htmlEscapes is allocated thanks to the check to see if is nil and never deallocated. This is technically a leak but it can be ignored safely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜