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 ?

alecail
  • 3,993
  • 4
  • 33
  • 52

1 Answers1

0

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)]);
  }
}
Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
  • I like the third one, performSelector. Having a Qt4 background, I'm wondering if this kind of call is also called a metacall in Objective-C ? – alecail Jul 05 '12 at 21:51
  • I'm not sure what a metacall is, but it's probably similar... though you may be interested in knowing that it's essentially how all methods are called in Objective-C... they are resolved at runtime via a selector-to-method lookup which is completely dynamic. – Chris Trahey Jul 05 '12 at 21:53
  • I would define it as a method call on an instance of the Class object of this instance. (Sorry, it's a bit tricky to define properly as english is not my mother tongue. QMetaObject is the concept I'm referring to.) – alecail Jul 05 '12 at 22:32
  • Ah, then no, that's not what is happening here; but Objective-C *does* have that feature. We call them 'class methods', and there even is this 'meta object'; in fact our classes are actual objects themselves. If you are looking at a header file, any method that begins with a dash (like `-(void) foo;`) is an instance method, and a plus-sign denotes a class method `+(MyClass *) getInstance;` – Chris Trahey Jul 05 '12 at 22:36