A. 不可变字符串
1 void stringCreate() 2 { 3 //Don't need to release memory by this way 4 NSString *str1 = @"String Sample"; 5 6 NSString *str2 = [[NSString alloc] init]; 7 str2 = @"String sample 2"; 8 [str2 release]; 9 10 NSString *str3 = [[NSString alloc] initWithString:@"String sample 3"]; 11 [str3 release]; 12 //Don't need to manage memory by static function 13 str3 = [NSString stringWithString:@"A String"]; 14 15 NSString *str4 = [[NSString alloc] initWithUTF8String:"String sample4"]; 16 [str4 release]; 17 //No manual memory management, too 18 str4 = [NSString stringWithUTF8String:"String 4"]; 19 20 21 NSString *str5 = [[NSString alloc] initWithFormat:@"My age is %i and height is %.2f", 19, 1.55]; 22 NSLog(@"String 5 is %@", str5); 23 [str5 release]; 24 }
B. 从文件读取字符串
1 void readFromFile() 2 { 3 NSString *path = @"/Users/hellovoidworld/Study/Foundation/NSString/file.txt"; 4 5 //This function cannot read Chinese, is expired 6 // NSString *str1 = [NSString stringWithContentsOfFile:path]; 7 8 NSError *error; 9 10 NSString *str1 = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; 11 12 if (error == nil) 13 { 14 NSLog(@"Read successfully, is %@", str1); 15 } 16 else 17 { 18 NSLog(@"Read fail, error is %@", error); 19 } 20 }
C. 从URL读取
1 void readFromUrl() 2 { 3 NSURL *url = [NSURL URLWithString:@"file:///Users/hellovoidworld/Study/Foundation/NSString/file.txt"]; 4 NSString *str2 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 5 NSLog(@"Read url successfully, is %@", str2); 6 }