Objective-c之NSString对象的创建(1)

//简单的定义 
NSString *aString = @"NSString创建的对象"; 
NSLog(aString);


//不需要分配内存空间和初始化 
NSString *tt = [NSString stringWithFormat:@"hello"];
NSLog(@"%@",tt);
[tt release]; 


//需要分配内存空间和初始化,使用完后需要release  释放 
NSString *pp = [[NSString alloc]initWithFormat:@"hello"];
NSLog(@"%@",pp);
[pp release];


//把已经存在的NSString对象赋值给新的对象:
NSString *t = [NSString stringWithString:tt];
NSString *p1 = [[NSString alloc]initWithString:pp];


//创建临时字符串
NSString *nstring = [NSString stringWithCString:"临时字符串"];
NSLog(@"nstring:%@",nstring); //不需要释放空间


//创建格式化字符串
int i = 1;
int j = 2;
//可分开写 
NSString *string = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%d.This is %i string!",i,j]];
NSLog(@"string:%@",string);
[string release];


//读取文件 
NSString *tring1 = @"string.txt";
NSString *tring2 = [[NSString alloc] initWithContentsOfFile:tring1];
NSLog(@"tring:%@",tring2);
[tring2 release];
 

//把字符串写到文件中    
NSString *astring = [[NSString alloc] initWithString:@"把字符串写到文件中!"];
NSString *path = @"astring.txt";    
[astring writeToFile: path atomically: YES];
//atomically 参数的值是BOOL类型,用于通知Cocoa是否应该首先将文件内容保存在临时文件中,
//当文件成功保存后,再将该临时文件和原始文件交换,这是一种安全机制 
[astring release];


 

你可能感兴趣的:(Objective-C)