使用 NSString 作为 NSString 数组?
我刚刚看到一行由同事编写的代码,我以前从未在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于没有 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 withNSString*
, perfectly valid but quite different from anNSArray
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.他正在使用 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 *) withnumberOfStrings
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.