[NSString dataUsingEncoding allowLossyConversion]
Returns an
NSData
object containing a representation of the receiver encoded using a given encoding.
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag
Parameters
- encoding
- A string encoding.
- flag
- If
YES
, then allows characters to be removed or altered in conversion.
Return Value of [NSString dataUsingEncoding allowLossyConversion]
An
NSData
object containing a representation of the receiver encoded using encoding. Returns nil
if flag is NO
and the receiver can’t be converted without losing some information (such as accents or case).Discussion of [NSString dataUsingEncoding allowLossyConversion]
If flag is
YES
and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding
toNSASCIIStringEncoding
, the character ‘Á’ becomes ‘A’, losing the accent.
This method creates an external representation (with a byte order marker, if necessary, to indicate endianness) to ensure that the resulting
NSData
object can be written out to a file safely. The result of this method, when lossless conversion is made, is the default “plain text” format for encoding and is the recommended way to save or transmit a string object.
Example of [NSString dataUsingEncoding allowLossyConversion]
NSString *myAccentStr = @"José";
char str[[myAccentStr length] + 1];
// NSString * to C String (char*)
NSData *strData = [myAccentStr dataUsingEncoding:NSMacOSRomanStringEncoding
allowLossyConversion:YES];
memcpy(str, [strData bytes], [strData length] + 1);
str[[myAccentStr length]] = '\0';
NSLog(@"str (from NSString* to c string): %s", str);
// C String (char*) to NSString *
NSString *newAccentStr = [NSString stringWithCString:str
encoding:NSMacOSRomanStringEncoding];
NSLog(@"newAccentStr (from c string to NSString*): %@", newAccentStr);
Example of [NSString dataUsingEncoding allowLossyConversion]
NSString *geoXValue = @"1.2343243";
NSString *geoYValue = @"1.5646546";
NSString *post = [NSString stringWithFormat:@"geoX%@ geoY%@", geoXValue, geoYValue];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
Example of [NSString dataUsingEncoding allowLossyConversion]
// original string
NSString *str = @"ÁlgeBra";
// convert to a data object, using a lossy conversion to ASCII
NSData *asciiEncoded = [str dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
// take the data object and recreate a string using the lossy conversion
NSString *other = [[NSString alloc] initWithData:asciiEncoded
encoding:NSASCIIStringEncoding];
// relinquish ownership
[other autorelease];
// create final capitalized string
NSString *final = [other capitalizedString];