Objective-C 中使用 NSArray 的指针数组
我正在为我的 iPhone 编写程序,有一个问题。
假设我有一个名为 my_obj 的类,
class my_obj
{
NSString *name;
NSinteger *id;
NSinteger *foo;
NSString *boo;
}
现在我从 my_obj 类型分配 100 个对象,并将它们插入到 NSArray 类型的数组中。
然后我想以两种不同的方式对数组进行排序。一个是名字,第二个是
身份证号。
我想从 NSArray 类型中分配另外两个数组,
*arraySortByName
*arraySortById
如果我只想将排序后的数组引用到原始数组,我需要做什么
所以我会得到两个指向原始数组的排序数组(没有改变!)
换句话说,我不想为每个排序数组分配另外 100 个对象。
I am writting program for my iphone and have a qestion.
lets say i have class named my_obj
class my_obj
{
NSString *name;
NSinteger *id;
NSinteger *foo;
NSString *boo;
}
now i allocate 100 objects from type my_obj and insert them to array from type NSArray.
then i want to sort the Array in two different ways. one by the name and the second by
the id.
i want to allocate another two arrays from type NSArray
*arraySortByName
*arraySortById
what i need to do if i just want the sorted arrays to be referenced to the original array
so i will get two sorted arrays that point to the original array (that didnt changed!)
i other word i dont want to allocate another 100 objects to each sorted array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
NSArray
方法sortedArrayUsingFunction:context:
(或其他 NSArray 排序函数)返回一个新数组。从文档中:
如果您的意思是排序后的数组应该只是指向原始数组的指针,那么这应该如何工作?排序数组中元素的顺序不同。
或者我没听懂你的问题。
You can use the
NSArray
methodsortedArrayUsingFunction:context:
(or the other NSArray sort functions) which returns a new array.From the documentation:
If you mean that the sorted arrays should just be pointers to the original array, how is this supposed to work? The order of the elements in the sorted arrays is different.
Or I didn't get your question.
这真的很容易。检查一下:
这将不会创建对象的副本。因此,您仍然只有 100 个已分配的
my_obj
对象。This is really easy. Check it:
This will not create copies of your objects. So you will still have only 100 allocated
my_obj
objects.