obj-C/Cocoa passing parameters of unknown class (but common parentage) to method. Possible?
I have a collection of classes defined from UIView.
@interface {
UIView *thisView
UIView *thatView
}开发者_StackOverflow中文版
...
thisView *viewOne = [[thisView alloc] init];
thatView *viewTwo = [[thatView alloc] init];
Now, say I want to create a method that will take these objects and call a function that is common to them both and also set common parameters and do all kinds of unbeknownst things, how do I pass these objects on to it if they are of different classes (assuming they are quite dissimilar)?
[self exampleMethod:viewOne];
[self exampleMethod:viewTwo];
- (void)exampleMethod:(UIView *)viewNumber //will this suffice?
{
[viewNumber anotherMethod];
...
The two most common practices are:
Make a
UIView
subclass (exampleClass
) that contains all the "things in common" – methods, properties, etc. – and then define yourthisView
andthatView
classes as subclasses ofexampleClass
. You can then useexampleClass
as the parameter in yourexampleMethod
.Create a protocol, and then have
thisView
andthatView
implement the protocol.
Both of these techniques are fundamental to Objective-C (and to object-oriented programming), and it's probably worth learning more about them before you invest a lot of time writing code.
If there is a common parent class that responds to the messages you're planning to send, you can type the variable as that. Otherwise, you can create a protocol that specifies the common interface.
if you want to use generic objects you can check to see if they respond to the message you want to perform. Then perform the message.
id blah;
if ([blah respondsToSelector:@selector(someMethod:)])
{
[blah performSelector:@selector(someMethod:) withObject:anObject];
}
for your example
- (void)exampleMethod:(UIView *)viewNumber //will this suffice?
{
if ([viewNumber respondsToSelector:@selector(anotherMethod)])
{
[viewNumber performSelector:@selector(anotherMethod)];
}
}
精彩评论