2010-06-21 34 views
1

我想我會嘗試創建一個簡單的可可應用程序。這是一個簡單的用於reddit的收件箱通知程序。我引入了一堆網址,並希望爲每個網址製作菜單項,並提供指向該網頁的鏈接。我想動態地設置每個動作的動作。我需要將URL傳遞給方法,所以它知道去哪裏。我有一種感覺,我做這一切都是錯誤的。有人能指引我走向正確的方向嗎?我想創建一個NSURL並將其發送到loadMessage。可可 - 通過setAction參數

NSURL *tempURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.reddit.com%@", [[message objectForKey:@"data"] objectForKey:@"context"]]]; 

[temptItem setAction:@selector(loadMessage:messageUrl:)]; 

回答

1

該選擇器不是有效的動作消息。操作可以接受一個參數或不接受;如果它們接受一個參數,則在參數中傳遞的對象將是發送該消息的控件。

你需要做的是在控制器中創建一個方法,用正確的對象調用loadMessage:messageURL:方法。

+0

好的,但我該如何將URL與每個菜單項相關聯? – polygone 2010-06-22 00:26:25

1

正如Chuck所說,那個選擇器有錯誤的形式。一種方法是使用-representedObject來例如該項目與一個URL相關聯:

- (void)menuAction:(id)sender { 
    [[NSWorkspace sharedWorkspace] openURL:[sender representedObject]]; 
} 

// adding an item: 
NSURL *url = [NSURL URLWithString:@"http://google.com/"];  
NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:@"moo" 
        action:@selector(menuAction:) keyEquivalent:@""] autorelease]; 
[item setTarget:self]; 
[item setRepresentedObject:url]; 
[item setEnabled:YES];  
// insert into menu 
+0

我試過這個,雖然它沒有出錯,但它不起作用。我嘗試了以下方法聲明的建議。 (IBAction)menuLoadMessage:(id)sender { \t [self loadMessage:[sender representObject]]; [code] [code] - (void)loadMessage:(NSURL *)messageUrl { \t [[NSWorkspace sharedWorkspace] openURL:messageUrl]; } [/ code] – polygone 2010-06-22 00:28:02

+0

@user:您是否在項目上使用了'-setRepresentedObject:'? – 2010-06-22 00:38:18

+0

NSURL * tempURL = [NSURL URLWithString: [NSString stringWithFormat:@「http://www.reddit.com%@」,[[message objectForKey:@「data」] objectForKey:@「context」]]]; \t \t [tempItem setRepresentedObject:tempURL]; [tempItem setAction:@selector(menuLoadMessage :)]; – polygone 2010-06-22 02:20:14