使用 NSString 作为 NSString 数组?

发布于 2024-12-27 00:05:33 字数 469 浏览 4 评论 0原文

我刚刚看到一行由同事编写的代码,我以前从未在 Obj-C 中见过它。它看起来形式很差,我想更改它,但它似乎有效(应用程序按预期工作),我什至不知道将其更改为什么。

NSString **stringArray= new NSString *[numberOfStrings];

这样可以吗? NSString 的 NSArray 会更有意义吗?

编辑:为了正确地从内存中释放数组,是否需要任何 release 调用?目前,我看到的只是delete [] stringArray;

编辑2:这似乎正确地从内存中删除数组:

for (int i=0; i < numberOfStrings; i++)
{
    [stringArray[i] release];
}
delete [] stringArray;

I just came across a line of code that was written by a co-worker and I've never seen this before in Obj-C. It looks like poor form and I want to change it, but it seemingly works (the app is working as expected) and I don't even know what to change it to.

NSString **stringArray= new NSString *[numberOfStrings];

Is this OK? Would an NSArray of NSStrings make more sense?

EDIT: In order to properly free the array from memory, are any release calls needed? Currently, all I see is delete [] stringArray;.

EDIT 2: This seems to properly remove the array from memory:

for (int i=0; i < numberOfStrings; i++)
{
    [stringArray[i] release];
}
delete [] stringArray;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乜一 2025-01-03 00:05:33

对于没有 C 背景的人来说,使用 NSArray 可能更容易理解,这只是一个填充了 NSString* 的普通旧 C 数组,完全有效,但与 完全不同>NSArray 实例。

两者都有道理,但如果该数组的用户期望 C 样式数组而不是 NSArray 实例,则可能需要进行大量重构。

Using an NSArray might be more legible to someone without a C background, this is just a plain old C array filled with NSString*, perfectly valid but quite different from an NSArray instance.

Both make sense, but if the users of that array are expecting a C-style array rather than an NSArray instance, there might be a lot of refactoring involved.

So要识趣 2025-01-03 00:05:33

他正在使用 Objective-C++(您应该能够在 xcode4 中文件右侧面板的“文件类型”中验证这一点)。

new 关键字创建一个新的 (NSString *) 数组,其大小为 numberOfStrings

为了回答您的问题,NSArray 很可能更易于管理,尤其是在代码有不同的开发人员的情况下。使用 C++ 数组可能会出现性能问题,但这取决于该代码的上下文。

He is using Objective-C++ (you should be able to verify that in the 'file type' on the right panel for the file in xcode4).

the new keyword is creates a new array of (NSString *) with numberOfStrings size.

To answer your question, an NSArray would very likely be more manageable, especially if there are different developers on the code. To use a C++ array there may have been performance issues but that depends on the context of that code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文