How to loop through subviews in order to get the text of NSTextViews

半城伤御伤魂 提交于 2020-01-16 11:56:58

问题


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 ?


回答1:


You can probably just do a simple cast to get the compiler's acceptance. You can do it with either a local variable, or a more complicated inline cast:

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

or

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

EDIT: I wil mention what we call "Duck Typing"... You might consider asking the object if it responds to the selector you want to send, instead of if it's the class you expect (if it quacks like a duck, it is a duck...).

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


来源:https://stackoverflow.com/questions/11352811/how-to-loop-through-subviews-in-order-to-get-the-text-of-nstextviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!