String em Objective-C
Posted: fevereiro 6th, 2009 | Author: Carlan Calazans | Tags: aprendizado, dev, iphone, mac, objectivec | No Comments »Quando falamos de String em Objective-C estamos nos referindo as classes NSString e NSMutableString. Como no C, Strings são basicamente um array de caracteres Unicode.

String Theory from xkcd.com
Por que duas classes?
A diferença entre elas é que uma é imutável ( NSString ) e a outra ( NSMutableString ) pode ser modificada. No entanto, é possível atribuir uma nova string em um ponteiro para a classe NSString. Dito isso, fica claro distinguir quando usar as classes mencionadas.
Abaixo temos pedaços de códigos com algumas (não todas) operações disponíveis.
NSString *firstName = @"Carlan";
NSString *lastName = [NSString string]; // or [[NSString alloc] init]
lastName = @"Calazans";
char cStr[15] = "An old C string";
NSString *cString = [NSString stringWithCString:cStr];
NSMutableString *fullNameMutable = [firstName mutableCopy];
// interpolation
NSString *fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
NSLog(@"My name is: %@", fullName);
printf("%s", [fullName cString]);
// basic operations
//[firstName appendString:@" Calazans"]; // wont compile
[fullNameMutable appendString:lastName];
[fullNameMutable lowercaseString];
[fullNameMutable uppercaseString];
[fullNameMutable capitalizedString];
[fullNameMutable length];
[fullName writeToFile:@"/tmp/test.txt" atomically: YES];
[fullNameMutable replaceString:@"Carlan" withString:@"Alan"];
NSRange r = NSMakeRange(0,4); // NSRange is not a class!
[fullNameMutable substringWithRange:r];
[fullNameMutable substringToIndex:4];
[fullNameMutable substringFromIndex:4];
NSMutableString *stringWithSpaces = [@" my string " mutableCopy];
[stringWithSpaces trimLeadSpaces];
[stringWithSpaces trimTailSpaces];
[stringWithSpaces trimSpaces];
NSString *strA = @"stringA";
NSString *strB = @"stringB";
[string1 compare:string2];
[string1 caseInsensitiveCompare:string2];
NSString *splitMe = @"carlan:calazans:29:brasileiro";
[splitMe componentsSeparatedByString:@":"];
Procurei deixar bem poucos comentários para não sujar muito o código. Não fica tão complicado de ler por que o nome dos métodos já dizem o que eles fazem.
Leave a Reply