迭代 NSTableview 或 NSArrayController 来获取数据
我有一个绑定到 NSArrayController 的 NSTableview。表/数组控制器包含核心数据“人”实体。人员由 GUI 用户添加到 NSTableview 中。
假设一个人实体看起来像
NSString* Name;
int Age;
NSString* HairColor;
现在我想迭代数组控制器中存储的内容以在其中执行某些操作。我想要做的实际操作并不重要,我真的不想陷入我试图对信息做什么的困境。它只是迭代 NSArraycontroller 中保存的所有内容,这让我感到困惑。我有 C++ 和 C# 背景,对 Cocoa 很陌生。假设我想构建一个 NSMutableArray,其中包含 1 年后来自 nsarraycontroller 的每个人。
所以我想做一些类似的事情,
NSMutableArray* mutArray = [[NSMutableArray alloc] init];
foreach(PersonEntity p in myNsArrayController) // foreach doesn't exist in obj-c
{
Person* new_person = [[Person alloc] init];
[new_person setName:p.name];
[new_person setHairColor:p.HairColor];
[new_person setAge:(p.age + 1)];
[mutArray addObject:new_person];
}
我相信唯一阻止我做类似上面代码的事情是 Obj-c 中不存在 foreach 。我只是不知道如何迭代 nsarraycontroller。
注意:这是针对 OSX 的,所以我打开了垃圾收集
I have an NSTableview which s bound to a NSArrayController. The Table/Arraycontroller contains Core Data "Person" entities. The people are added to the NSTableview by the GUI's user.
Let's say a person entity looks like
NSString* Name;
int Age;
NSString* HairColor;
Now I want to iterate over what is stored in the array controller to perform some operation in it. The actual operation I want to do isn't important I don't really want to get bogged down in what I am trying to do with the information. It's just iterating over everything held in the NSArraycontroller which is confusing me. I come from a C++ and C# background and am new to Cocoa. Let's say I want to build a NSMutableArray that contains each person from nsarraycontroller 1 year in the future.
So I would want to do something like
NSMutableArray* mutArray = [[NSMutableArray alloc] init];
foreach(PersonEntity p in myNsArrayController) // foreach doesn't exist in obj-c
{
Person* new_person = [[Person alloc] init];
[new_person setName:p.name];
[new_person setHairColor:p.HairColor];
[new_person setAge:(p.age + 1)];
[mutArray addObject:new_person];
}
I believe the only thing holding me back from doing something like the code above is that foreach does not exist in Obj-c. I just don't see how to iterate over the nsarraycontroller.
Note: This is for OSX so I have garbage collection turned on
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找快速枚举。
对于你的例子,类似
You're looking for fast enumeration.
For your example, something like
您还可以使用块进行枚举。例如:
两种方法各有利弊。这些在这个问题的答案中进行了深入讨论:
Objective-C enumerateUsingBlock vs fast enumeration?
您可以在 Apple 的 WWDC 2010 视频中找到有关块的精彩教程。他们说在苹果公司“一直”使用块。
You can also enumerate using blocks. For example:
There's pro's and cons to both approaches. These are discussed in depth in the answer to this question:
Objective-C enumerateUsingBlock vs fast enumeration?
You can find a great tutorial on blocks in Apple's WWDC 2010 videos. In that they say that at Apple they use blocks "all the time".