使用 NSMenuItems 更新动态创建的 NSMenu
我有一个 NSMenu,其中有 3 个我想保留的静态 NSMenuItems,之后的一堆是动态生成的,每次用户单击菜单图标时都应该删除并重新加载。
我试图创建一个弹出的进程列表,但每次打开弹出窗口时, NSMenuItems 都不会清除。他们只是以某种时髦的方式添加。记录 for 循环表明循环尚未完成。有什么想法吗?
-(void)menuNeedsUpdate:(NSMenu *)menu{
//Keep Top 3 Menu Items
if(dropDown.numberOfItems > 3){
NSLog(@"-----------Removing Items");
NSLog(@"%d",itemCount);
for(int i = 2; i <= dropDown.numberOfItems; i++){
NSLog(@"%d",i);
[dropDown removeItemAtIndex:i];
}
}
NSArray *appArray = [[NSWorkspace sharedWorkspace] runningApplications];
for (NSRunningApplication *r in appArray){
//NSLog(r.localizedName);
//NSLog(@"------------");
NSMenuItem *i = [[NSMenuItem alloc] initWithTitle:r.localizedName
action:@selector(fooClicked:) keyEquivalent:@""];
[i setTarget:self];
[dropDown addItem:i];
[i release];
}
}
I have a NSMenu with 3 static NSMenuItems that I want to keep, and a bunch after that are dynamically generated and should be removed and reloaded each time the user clicks the menu icon.
I'm trying to create a list of processes that pop out, but each time I open the popout, the NSMenuItems don't clear. They just add on in some funky way. Logging the for loop shows that the loop isn't completing. Any ideas why?
-(void)menuNeedsUpdate:(NSMenu *)menu{
//Keep Top 3 Menu Items
if(dropDown.numberOfItems > 3){
NSLog(@"-----------Removing Items");
NSLog(@"%d",itemCount);
for(int i = 2; i <= dropDown.numberOfItems; i++){
NSLog(@"%d",i);
[dropDown removeItemAtIndex:i];
}
}
NSArray *appArray = [[NSWorkspace sharedWorkspace] runningApplications];
for (NSRunningApplication *r in appArray){
//NSLog(r.localizedName);
//NSLog(@"------------");
NSMenuItem *i = [[NSMenuItem alloc] initWithTitle:r.localizedName
action:@selector(fooClicked:) keyEquivalent:@""];
[i setTarget:self];
[dropDown addItem:i];
[i release];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是删除代码。考虑一下:
最后应该是
i--
。另外 - 如果数组有 3 个项目,则最后一个项目的索引为 2,因此循环的声明应如下所示:根据注释更新 从
菜单中删除项目应向后或向前执行,但在第二个项目之后立即删除相同的项目索引(即始终删除第三个项目):
或者
这是必需的,因为每次删除第 i 个项目时,项目数组都会缩短,有时您会击中该对象这超出了数组范围。考虑这种情况:
这可以解释“时髦的方式”。
your problem is with removal code. Consider this:
It should be
i--
at the end. Also - if array has 3 items, the index of last item is 2, hence the declaration of the loop should be following:Update according to comment
Removing the items from your menu should be performed backwards or forward, but removing same item index right next after the 2nd item (i.e. removing always 3rd item):
or
This is needed because each time you remove
i
th item, the array of items shortens and sometimes you hit the object that is beyond array bounds. Consider this scenario:i
th itemThis would explain the "funky way".