Sunday, May 19, 2013

NSString smallestEncoding example ios


[NSString smallestEncoding]

Returns the smallest encoding to which the receiver can be converted without loss of information.
- (NSStringEncoding)smallestEncoding
Return Value
The smallest encoding to which the receiver can be converted without loss of information.
Discussion of [NSString smallestEncoding]
The returned encoding may not be the fastest for accessing characters, but is space-efficient. This method may take some time to execute.
Example of [NSString smallestEncoding]
 NSStringEncoding stringEncoding =  [contentString smallestEncoding];
    CFStringEncoding cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(stringEncoding);
    CFStringRef cfStringEncodingName =  CFStringGetNameOfEncoding(cfStringEncoding);
    NSString *encodingName = (__bridge NSString *)cfStringEncodingName;
    
    if (encodingName == nil || [encodingName isEqualToString:@\"\"]) {
        encodingName = @\"utf-8\";
    }
Example of [NSString smallestEncoding]

- (BOOL)writeWithAuthorizationToURL:(NSURL *)absoluteURL error:(NSError **)outError;
{
    BOOL result = NO;
    NSString * string = [textStorage string];
    NSData * data = nil;
  
    // Get String Data
    data = [string dataUsingCFStringEncoding:textEncoding addBOM:saveWithBOM];
    if (!data) data = [string dataUsingEncoding:[string smallestEncoding]];
    if (!data) {
        *outError = [NSError errorWithDomain:AraeliumEditErrorDomain code:WBErrorCodeCantCreateDataFromString userInfo:nil];
        return NO;
    }
  
    // Write to a temporary file
    NSString * path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[absoluteURL relativePath] lastPathComponent]];
    if (![data writeToURL:[NSURL fileURLWithPath:path] options:NSAtomicWrite error:outError]) {
        NSLog(@"Couldn't write to temporary file.");
        *outError = [NSError errorWithDomain:NSCocoaErrorDomain code:513 userInfo:nil];
        return NO;
    }
  
    // Move temporary file into place
    char *args[3]; // arguments for the mv command
    args[0] = "-f"; // force the mv so it won't ask for confirmation
    args[1] = (char *)[path fileSystemRepresentation]; // path of file to move
    args[2] = (char *)[[absoluteURL relativePath] fileSystemRepresentation]; // location to move to
    args[3] = NULL; // terminate the args
    OSStatus myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef, "/bin/mv", 0, args, NULL);
  
    // Handle the result
    if (myStatus != noErr) {
        *outError = [NSError errorWithDomain:NSCocoaErrorDomain code:513 userInfo:nil];
        NSLog(@"Error moving file");
        result = NO;
    } else {
        result = YES;
    }
  
    return result;
}