gpt4 book ai didi

objective-c - 定义 NSMutableString?

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

我的理解是这两个都创建了一个NSMutableString,只有第一个归系统所有,第二个归我所有(即我需要释放它)。我应该使用一个或另一个有什么特别的原因吗,从表面上看,使用第一个似乎更容易?第一个更好吗,因为它给了编译器一种大小感?

NSMutableString *newPath = [NSMutableString stringWithCapacity:42];

NSMutableString *newPath = [[NSMutableString alloc] init];

编辑...还有

我看到很多声明写在两行上(即)

NSMutableString *newPath;
newPath = [NSMutableString stringWithCapacity:42];

我个人更喜欢单线,这是个人风格的另一个例子吗?

最佳答案

NSMutableString *newPath = [NSMutableString stringWithCapacity:42];

OR

NSMutableString *newPath = [[NSMutableString alloc] init];

Is there any particular reason why I should use one or the other, on the face of it it seems easier to use the first?

是的。除非有特殊原因,否则始终立即自动释放。

第一个原因是很容易忘记编写 release 消息。如果您在创建对象的同一条语句中自动释放对象(如 [[[... alloc] init] autorelease]),忘记它就更难,忘记它也更明显.方便的工厂方法(例如 stringWithCapacity:)会为您自动释放对象,因此就像您自己自动释放它一样,您不必担心稍后会释放它。

其次,即使您确实记得编写单独的 release 消息,也很容易不命中它。提前返回有两种方式:

NSString *str = [[NSString alloc] initWithString:@"foo"];

BOOL success = [str writeToFile:path atomically:NO];
if (!success)
return;

[str release];

并抛出或传播异常:

NSString *str = [[NSString alloc] initWithString:@"foo"];

//Throws NSRangeException if str is not in the array or is only in the array as the last object
NSString *otherStr = [myArray objectAtIndex:[myArray indexOfObject:str] + 1];

[str release];

“不这样做的具体原因”通常是您有一个创建大量对象的紧密循环,在这种情况下,您可能希望尽可能多地手动管理循环中的对象,以保持你的对象倒计时。但是,只有在您有证据表明这是您的问题时才这样做(无论是来自 Shark 的硬数字,来自 Instruments 的硬数字,还是只要循环运行足够长的时间,您的系统就会进入分页 hell )。

其他可能更好的解决方案包括将循环拆分为两个嵌套循环(外部循环为内部循环创建和排出自动释放池)并切换到 NSOperation。 (但是,请确保您对队列一次运行的操作数设置了限制——否则,you may make it even easier to go into paging hell。)

Also is the first better as it gives the compiler a sense of size?

更好,但不是那个原因。

对于编译器来说,它只是另一个类消息。编译器不知道也不关心它做了什么;对于它所知道和关心的一切,stringWithCapacity: 是向用户播放歌曲的消息。

它确实为 NSMutableString 提供了一个大小提示——该类将知道它最初可能想要分配多少字符存储空间。您从中获得的任何好处都可能很小(至少在 Mac 上如此),但如果您手边有这些信息,为什么不使用它呢?相反,我不会特意去计算它。

I see a lot a declarations written on two lines (i.e.)

NSMutableString *newPath;
newPath = [NSMutableString stringWithCapacity:42];

Personally I prefer the one-liner, is this just another example personal style?

是的。但是,让变量未初始化存在一定的风险。如果您决定养成这种习惯,请务必打开“运行静态分析器”build设置。

关于objective-c - 定义 NSMutableString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1487731/

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