为什么NSString stringWithString返回指向复制字符串的指针? [英] Why is NSString stringWithString returning pointer to copied string?

查看:85
本文介绍了为什么NSString stringWithString返回指向复制字符串的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将NSString值从NSMutableArray中复制到新变量中. NSString stringWithString返回的NSString具有与我的数组中的对象相同的内存地址.为什么?

I'm trying to copy an NSString value out of an NSMutableArray into a new variable. NSString stringWithString is returning an NSString with the same memory address as the object in my array. Why?

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSMutableArray *arr = [NSMutableArray arrayWithObject:@"first"];

        NSLog(@"string is '%@' %p", [arr objectAtIndex:0], [arr objectAtIndex:0]);

        // copy the string
        NSString *copy = [NSString stringWithString:[arr objectAtIndex:0]];
        NSLog(@"string is '%@' %p", copy, copy);

    }
    return 0;
}

推荐答案

1)每当使用@""语法创建字符串时,框架都会自动缓存该字符串. NSString是一个非常特殊的类,但是框架会照顾它.当您在应用的多个位置使用@"Some String"时,它们都将指向内存中的相同地址.仅当使用-initWithData:encoding之类的字符串时,该字符串才会被缓存.

1) Whenever you're creating a string using the @"" syntax, the framework will automatically cache the string. NSString is a very special class, but the framework will take care of it. When you use @"Some String" in multiple places of your app, they will all point to the same address in memory. Only when you're using something like -initWithData:encoding, the string won't be cached.

2)其他答案建议您应该改用-copy,但是-copy仅在对象可变时才创建该对象的副本. (例如NSMutableString)
当您将-copy发送到不可变对象(如NSString)时,将与发送-retain相同,后者将返回对象本身.

2) The other answers suggested that you should use -copy instead, but -copy will only create a copy of the object if the object is mutable. (like NSMutableString)
When you're sending -copy to an immutable object (like NSString), it'll be the same as sending it -retain which returns the object itself.

NSString *originalString = @"Some String";
NSString *copy = [originalString copy];
NSString *mutableCopy1 = [originalString mutableCopy];
NSString *mutableCopy2 = [mutableCopy copy];
NSString *anotherString = [[NSString alloc] initWithString:originalString];

-> originalStringcopymutableCopy2anotherString都将指向相同的内存地址,只有mutableCopy1点执行不同的内存区域.

--> originalString, copy, mutableCopy2 and anotherString will all point to the same memory address, only mutableCopy1 points do a different region of memory.

这篇关于为什么NSString stringWithString返回指向复制字符串的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆