Nsstring * string = @"My String";Nsstring * string = [[[Nsstring alloc] initWithString:@"MyString"] autorelease]解决方法 @“我的字符串”是一个字符串编译成二进制的字符串.加载时,它在内存中有一个位置.第一行声明一个指向内存中的那个点的变量.
从字符串编程指南:
The simplest way to create a string object in source code is to use
the Objective-C @”…” construct:
Nsstring *temp = @"/tmp/scratch";
Note that,when creating a string
constant in this fashion,you should avoID using anything but 7-bit
ASCII characters. Such an object is created at compile time and exists
throughout your program’s execution. The compiler makes such object
constants unique on a per-module basis,and they’re never deallocated,
though you can retain and release them as you do any other object.
第二行通过取字符串来分配一个字符串.请注意,@“我的字符串”字面字符串是相同的.证明这一点
Nsstring *str = @"My String";NSLog(@"%@ (%p)",str,str);Nsstring *str2 = [[Nsstring alloc] initWithString:@"My String"];NSLog(@"%@ (%p)",str2,str2);Nsstring *copy = [str2 stringByAppendingString:@"2"];NSLog(@"%@ (%p)",copy,copy);
输出相同的内存地址:
2011-11-07 07:11:26.172 Craplet[5433:707] My String (0x100002268)2011-11-07 07:11:26.174 Craplet[5433:707] My String (0x100002268)2011-11-07 07:11:26.174 Craplet[5433:707] My String2 (0x1003002a0)
什么是告诉不仅前两个字符串相同的内存地址,但如果不更改代码,它是每次运行它相同的内存地址.它在内存中是相同的二进制偏移量.但是,不仅复制不同,而且每次运行它都会因为在堆上分配而不同.
autorelease根据上述doc ref没有影响.你可以释放它们,但是它们永远不会被释放.所以,它们是相等的,因为两者都是自动释放的字符串,但是它们都是常量,并且释放被忽略.
总结以上是内存溢出为你收集整理的objective-c – NSString文字之间的区别全部内容,希望文章能够帮你解决objective-c – NSString文字之间的区别所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)