问题
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