0

I have a NSView which contains several instances of NSTextView. I would like to get the content (string) of each instance. So far, I have this (this code does not compile) :

for(NSView *view in [self subviews]) {
    NSLog(@"class: %@ ", [view className]);
if([view isKindOfClass:[NSTextView class]])
    NSLog(@"[view string] %@",[view string]);}

At this point, I expect to be able to send the string message to view which is an instance of NSTextView, but:

Error message: No visible @interface for 'NSView' declares the selector 'string'

Where is my error ?

4

1 回答 1

0

您可能只需进行简单的转换即可获得编译器的接受。您可以使用局部变量或更复杂的内联转换来做到这一点:

for(NSView *view in [self subviews]) {
  NSLog(@"class: %@ ", [view className]);
  if([view isKindOfClass:[NSTextView class]]) {
    NSTextView *thisView = (NSTextView *)view;
    NSLog(@"[view string] %@",[thisView string]);
  }
}

或者

for(NSView *view in [self subviews]) {
  NSLog(@"class: %@ ", [view className]);
  if([view isKindOfClass:[NSTextView class]])
    NSLog(@"[view string] %@",[(NSTextView *)view string]);
}

编辑:我会提到我们所说的“鸭子打字”......您可能会考虑询问对象它是否响应您要发送的选择器,而不是它是否是您期望的类(如果它像鸭子一样嘎嘎叫,它是鸭子...)。

for(NSView *view in [self subviews]) {
  NSLog(@"class: %@ ", [view className]);
  if([view respondsToSelector:@selector(string)]) {
    NSLog(@"[view string] %@",[view performSelector:@selector(string)]);
  }
}
于 2012-07-05T21:39:40.157 回答