2010-12-06 15 views
1

htmlの文字をエスケープするためのコードが見つかりました。私はこのコードについて質問があります。あなたが見ることができるように、それを "alloc"し、それを "解放"しません。メモリリークの原因になりますか?それは解放されなければならない?目的cメモリ管理

 
    htmlEscapes = [[NSDictionary alloc] initWithObjectsAndKeys: 
//  @"&", @"&", 
     @"<", @"", 
     @"'", @"'", 
     @""", @"\"",   
     nil 
     ]; 

おかげで...

クラス全体


 

#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 

答えて

3

はどうやら、NSDictionaryのインスタンスは1つだけ作成され、それが意図的に保存され、アプリケーションのライフタイムのために再利用されます。メモリリークは考慮されていません(少なくとも単一のスレッド環境ではありませんが、もちろん、ifステートメントでは潜在的な競合状態が可能です)。

3

Objective-Cでシングルトンを実装するための共通のパターンです。 htmlEscapesの1つのインスタンスは、ifがnilであり、割り当てが解除されていないことを確認するために割り当てられます。これは技術的に漏れですが、安全に無視することができます。