【问题标题】:I found warning in this method. Multiple method named 'state' found?我在这种方法中发现了警告。找到多个名为“状态”的方法?
【发布时间】:2013-05-19 00:54:30
【问题描述】:

我是 mac 开发的新手。这是我的代码,但我不明白这个警告。请帮帮我。

  - (IBAction)toggleFiles:(id)sender
  {
NSRect frame = [oWindow frame];
NSRect contentRect = [oWindow contentRectForFrameRect:frame];
float titlebarHeight = NSHeight(frame) - NSHeight(contentRect);

NSSize newSize = [sender state] == NSOnState ? sFilesExpandedSize : sFilesCollapsedSize;
frame.origin.y -= newSize.height - contentRect.size.height;
frame.size = newSize;
frame.size.height += titlebarHeight;

[oWindow setFrame:frame display:YES animate:YES];

[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:(int)  [sender state] == NSOnState]
                                           forKey:@"DisplayFiles"];
 }

在此处找到此警告 - 找到多个名为“状态”的方法。如何解决这个问题。请帮帮我。

【问题讨论】:

  • 什么是发件人类型?
  • Duck 打字与 Xcode 4.

标签: objective-c macos


【解决方案1】:

sender 被键入为id。这意味着编译器会将编译器知道的任何地方定义的所有方法都视为sender 可以响应的可能集合。

不幸的是,声明了两个(或更多)state 方法具有不同的论证。例如,一个可能返回BOOL,另一个可能返回NSUInteger

因此,编译器警告您在泛型类型 (id) 对象上调用 state 可能会产生意外结果,因为无法知道返回值的类型可能是什么。

解决方案?

要么将sender 静态输入到某个特定的类(即 -(IBAction)toggleFiles:(SomeClass*)sender;要么对返回值进行类型转换。

在任何一种情况下,将assert([sender isKindOfClass:[ExpectedClass class]); 之类的内容添加到该操作方法中以进行防御。

【讨论】:

  • 还要注意,通过将 sender 键入为 id,它允许您执行诸如让多个控件调用相同的 IBAction 方法,然后在方法内部根据发件人的类处理事情。跨度>
【解决方案2】:

谢谢你。这是我的答案。我解决了我的问题。

- (IBAction)toggleFiles:(id)sender
 {
NSRect frame = [oWindow frame];
NSRect contentRect = [oWindow contentRectForFrameRect:frame];
float titlebarHeight = NSHeight(frame) - NSHeight(contentRect);
   NSCell *cell =sender;
   Bool fleg = [cell state] == NSOnState;
NSSize newSize = fleg ? sFilesExpandedSize : sFilesCollapsedSize;
frame.origin.y -= newSize.height - contentRect.size.height;
frame.size = newSize;
frame.size.height += titlebarHeight;

[oWindow setFrame:frame display:YES animate:YES];

[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:[fleg
                                          forKey:@"DisplayFiles"];
}

我只在发件人之前添加 (NSCell * )。谢谢。

【讨论】:

  • 为了防御,我建议在演员阵容之前(或之后,没关系)在行中添加assert([sender isKindOfClass:[NSCell class]]);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多