gpt4 book ai didi

objective-c - NSString 文字之间的区别

转载 作者:太空狗 更新时间:2023-10-30 03:17:37 24 4
gpt4 key购买 nike

这两行有什么区别?

NSString * string = @"My String";
NSString * string = [[[NSString alloc] initWithString:@"MyString"] autorelease]

最佳答案

@"My String"是编译成二进制的文字字符串。加载时,它在内存中有一个位置。第一行声明了一个指向内存中那个点的变量。

来自字符串编程指南:

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.

第二行通过获取该文字字符串来分配一个字符串。请注意,两个@"My String"文字字符串是相同的。为了证明这一点:

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)

说明的是不仅前两个字符串内存地址相同,而且如果不更改代码,每次运行它都是相同的内存地址。它是内存中相同的二进制偏移量。但是,不仅副本不同,而且每次运行它时都不同,因为它是在堆上分配的。

根据上面的文档引用,自动释放没有影响。您可以释放它们,但它们永远不会被释放。因此,它们相等并不是因为它们都是自动释放的字符串,而是它们都是常量并且释放被忽略。

关于objective-c - NSString 文字之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8032375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com