Tuesday, May 14, 2013

NSString initWithContentsOfFile usedEncoding error example ios


[NSString initWithContentsOfFile usedEncoding error]

Returns an NSString object initialized by reading data from the file at a given path and returns by reference the encoding used to interpret the characters.
- (id)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
Parameters of [NSString initWithContentsOfFile usedEncoding error]
path
A path to a file.
enc
Upon return, if the file is read successfully, contains the encoding used to interpret the file at path.
error
If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, pass in NULL.
Return Value of [NSString initWithContentsOfFile usedEncoding error]
An NSString object initialized by reading data from the file named by path. The returned object may be different from the original receiver. If the file can’t be opened or there is an encoding error, returns nil.

Example of [NSString initWithContentsOfFile usedEncoding error]

NSStringEncoding enc;

NSString *result = [[NSString alloc] initWithContentsOfFile:fileName
                    usedEncoding: &enc
                    error:nil];

// Do something with the information about the encoding used
if ( enc == NSUTF8StringEncoding ) {
     // ...
}

return result;
Example of [NSString initWithContentsOfFile usedEncoding error]
    NSString *path = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"asc"];
    path = [path stringByExpandingTildeInPath];
    NSString *fileString = [NSString initWithContentsOfFile:path];
Example of [NSString initWithContentsOfFile usedEncoding error]
// Fill myString with questions from the .txt file and then read .txt file
NSString *filePath = whatFile; 
NSStringEncoding encoding;
NSError *error;
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath usedEncoding:&encoding error:&error];

if (!myString) {
  myString = [[NSString alloc] encoding:NSUTF8StringEncoding error:&error]
}

if (!myString) {
  myString = [[NSString alloc] encoding:NSISOLatin1StringEncoding error:&error]
}

if (!myString) {
  NSLog(@"error: %@", error);
  return;
}


// Load array
NSArray* myArray = [myString componentsSeparatedByString:@"\r"];
NSLog (@"\n \n Number of elements in myArray = %i", [myArray count]);