Dla iOS następujący kod powinien działać dla kodów numerycznych. Powinien on być stosunkowo łatwo rozszerzyć do m.in. &
...
-(NSString*)unescapeHtmlCodes:(NSString*)input {
NSRange rangeOfHTMLEntity = [input rangeOfString:@"&#"];
if(NSNotFound == rangeOfHTMLEntity.location) {
return input;
}
NSMutableString* answer = [[NSMutableString alloc] init];
[answer autorelease];
NSScanner* scanner = [NSScanner scannerWithString:input];
[scanner setCharactersToBeSkipped:nil]; // we want all white-space
while(![scanner isAtEnd]) {
NSString* fragment;
[scanner scanUpToString:@"&#" intoString:&fragment];
if(nil != fragment) { // e.g. '& B'
[answer appendString:fragment];
}
if(![scanner isAtEnd]) { // implicitly we scanned to the next '&#'
int scanLocation = (int)[scanner scanLocation];
[scanner setScanLocation:scanLocation+2]; // skip over '&#'
int htmlCode;
if([scanner scanInt:&htmlCode]) {
char c = htmlCode;
[answer appendFormat:@"%c", c];
scanLocation = (int)[scanner scanLocation];
[scanner setScanLocation:scanLocation+1]; // skip over ';'
} else {
// err ?
}
}
}
return answer;
}
Niektóre kodu Jednostka test ...
-(void)testUnescapeHtmlCodes {
NSString* expected = @"A & B";
NSString* actual = [self unescapeHtmlCodes:@"A & B"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
expected = @"& B";
actual = [self unescapeHtmlCodes:@"& B"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
expected = @"A &";
actual = [self unescapeHtmlCodes:@"A &"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
}
zrobiłem to samo ... ale czy jest jakiś sposób, aby wbudowane zrób to ... – nbojja
@nbojja Ile więcej wbudowałeś, ile chcesz? Jeśli to dotyczy, dodaj metodę, która robi to jako kategorię na NSString, a następnie jest wbudowana. – Abizern
@Abizern: Wiele języków ma wbudowane metody kodowania i dekodowania obiektów HTML, Obj-C brakuje tego i wielu innych rzeczy, które programiści biorą za pewnik od 2002 roku. Wyszukiwanie i zastępowanie jest złym substytutem, ponieważ będziesz musiał spędzić sporo czasu, aby wiedzieć, że dostajesz wszystkie jednostki. –