Sunday, May 12, 2013

NSString defaultCStringEncoding example ios


Returns the C-string encoding assumed for any method accepting a C string as an argument.
+ (NSStringEncoding)defaultCStringEncoding
Return Value
The C-string encoding assumed for any method accepting a C string as an argument.
Discussion( NSString defaultCStringEncoding example )
This method returns a user-dependent encoding who value is derived from user's default language and potentially other factors. You might sometimes need to use this encoding when interpreting user documents with unknown encodings, in the absence of other hints, but in general this encoding should be used rarely, if at all. Note that some potential values might result in unexpected encoding conversions of even fairly straightforward NSString content—for example, punctuation characters with a bidirectional encoding.( NSString defaultCStringEncoding example )
Methods that accept a C string as an argument use ...CString... in the keywords for such arguments: for example, stringWithCString:—note, though, that these are deprecated. The default C-string encoding is determined from system information and can’t be changed programmatically for an individual process. See “String Encodings” for a full list of supported encodings.
( NSString defaultCStringEncoding example )
NSString* myString= @"testing";

NSData* data=[myString dataUsingEncoding: [NSString defaultCStringEncoding] ];
( NSString defaultCStringEncoding example )
NSString *someString = @"string";

//NSString to NSData
NSData* data=[someString dataUsingEncoding: [NSString defaultCStringEncoding]];

//NSData to NSString
someString = [[NSString alloc] initWithData:data encoding:[NSString defaultCStringEncoding]];

NSLog(@"%@", someString);
( NSString defaultCStringEncoding example )
// Getting content of CSV file
NSError* error;
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"categories" ofType:@"csv"];
NSString* data = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:&error];
NSArray* categories = [data componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

for (int i = 0; i < categories.count; ++i) {
    NSString* cat = [categories objectAtIndex:i];
    NSLog(@"categorie : :%@:", [categories objectAtIndex:i]);
    NSString* decodedString = [NSString stringWithUTF8String:[cat cStringUsingEncoding:[NSString defaultCStringEncoding]]];
    NSLog(@"categorie : %@", decodedString);
    [self.categories addObject:decodedString];