2010-12-06 115 views
1

我發現了一個用於轉義html字符的代碼。我對此代碼有疑問。正如你可以看到它「alloc」並且不「釋放」它。它會導致內存泄漏嗎?它必須被釋放?objective 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只有一個實例,它的目的地存儲和應用程序的生命週期重用。它不被視爲內存泄漏(至少不在單線程環境中;當然,if聲明可能存在潛在競爭條件)。

3

這是在Objective-C中實現單例的常見模式。一個htmlEscapes實例被分配,因爲檢查是否爲零且永不釋放。這在技術上是泄漏,但可以安全地忽略。