[OC Foundation框架 - 2] NSString 的创建

A. 不可变字符串

 void stringCreate()
{
//Don't need to release memory by this way
NSString *str1 = @"String Sample"; NSString *str2 = [[NSString alloc] init];
str2 = @"String sample 2";
[str2 release]; NSString *str3 = [[NSString alloc] initWithString:@"String sample 3"];
[str3 release];
//Don't need to manage memory by static function
str3 = [NSString stringWithString:@"A String"]; NSString *str4 = [[NSString alloc] initWithUTF8String:"String sample4"];
[str4 release];
//No manual memory management, too
str4 = [NSString stringWithUTF8String:"String 4"]; NSString *str5 = [[NSString alloc] initWithFormat:@"My age is %i and height is %.2f", , 1.55];
NSLog(@"String 5 is %@", str5);
[str5 release];
}
 
B. 从文件读取字符串
 void readFromFile()
{
NSString *path = @"/Users/hellovoidworld/Study/Foundation/NSString/file.txt"; //This function cannot read Chinese, is expired
// NSString *str1 = [NSString stringWithContentsOfFile:path]; NSError *error; NSString *str1 = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; if (error == nil)
{
NSLog(@"Read successfully, is %@", str1);
}
else
{
NSLog(@"Read fail, error is %@", error);
}
}
 
C. 从URL读取
 void readFromUrl()
{
NSURL *url = [NSURL URLWithString:@"file:///Users/hellovoidworld/Study/Foundation/NSString/file.txt"];
NSString *str2 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"Read url successfully, is %@", str2);
}
 
 
 
上一篇:黑马程序员:Java编程_集合


下一篇:ntpdate