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 @"<", @"<",
@">", @">",
@"'", @"'",
@""", @"\"",
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:
// @"&", @"&",
@"<", @"<",
@">", @">",
@"'", @"'",
@""", @"\"",
nil
];
}
return htmlEscapes;
}
+ (NSDictionary *)htmlUnescapes {
if (!htmlUnescapes) {
htmlUnescapes = [[NSDictionary alloc] initWithObjectsAndKeys:
// @"&", @"&",
@"<", @"<",
@">", @">",
@"'", @"'",
@"\"", @""",
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.
精彩评论