Τετάρτη, 11 Απριλίου 2012

chars - c strings and NSString

notes from Big Nerd Ranch Guide - Objective C


CHAR
char = a byte could be treated as a number or a character. (0-127)

  • 0-31 ASCII - are unprintable control codes
  • 32 is the space character
  • 127 is the delete
The non-printable characters can expressed using escape sequences that start with \.
  • \0 = null byte (0x00)
C string
A C string is a series of characters right next to each other in memory. the string ends when the character 0x00 is encountered
  • char * test = malloc(5)
  • test[4]='\0'

String literals
You can create a pointer to a string of characters (terminated with the zero character) by putting the string in quotes.
  • char *start = "love";
DANGER: literals strings are CONSTANT. Don't try to change them!

To enable the compiler to warn you about writing to constant parts of memory, you can use the 
  • const modifier
  • const char * text= "test"; !Read-only variable is not assignable

C string to NSString
char *cstring = "ohmy!";
NSString *y = [NSString stringWithCstring:cstring encoding: NSUTF8StringEncoding];

NSString to C string
NSString *mystring = @"noway!";
const char *cstring = NULL;
        if ([mystring canBeConvertedToEncoding:NSUTF8StringEncoding]) {
            cstring = [mystring cStringUsingEncoding:NSUTF8StringEncoding];
        }

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου