views:

41

answers:

2

hi all,

i've got a small scenario to call fucntions in two different classes.

i have two classes names firstClass.m and secondClass.m

i want to call class1.m from class2.m

secondClass

method { variables 1 & 2; call method in class1 }

firstClass

method { NSLog("printing variables 1 & 2 of secondClass.m"); }

i want to knw how to call firstClass method and send those variables to the the class for printing.

thank you

A: 

Depending on the type of function you want to call you could create a static function. To do so just declare the function like + (void)printA:(int)a andB:(int)b;

and call it with [Class2 printA:a andB:b] without an instance. Or if you want to call a non static method you could use a delegation protocol.

You can create a protocol like

@protocol PrintJobReceiver
- (void)printVariableA:(int)a andB:(int)b;
@end

have it be conformed by class2

@interface Class2: NSObject <PrintJobReceiver> { }
@end
@implementation Class2
- (void)printVariableA:(int)a andB:(int)b
{
   NSLog(@"a: %i b:%i",a,b);
}
@end

and set a delegate at Class1 you will then use to print (you will want to pass an instance of Class2)

@interface Class1:NSObject
{
   id<PrintJobReceiver> delegate;
}
@property (nonatomic,readwrite, retain) id<PrintJobReceiver> delegate;
@end
@implementation Class1
@synthesize delegate;
@end

then you can call [delegate printVariableA:a andB:b]; within Class1. I usually use this instead of passing a reference to the whole class in order to only show the functions that are supposed to be used by the class (and you don't get tempted to use functions you shouldn't)

dkk
A: 

@dkk

I've implemented your solution but...

[delegate printVariableA:a andB:b];

don't work because delegate was nil. How it's possible? I forget something?

thanks for your reply.

pask
You have to set the delegate to point to the delegate object.
Wade Williams
i'm a "learner"... how i can do it?My problem is that i don't want to re-alloc class (view controller) otherwise i lost data on textfields because instance is not the same (i think).thanks
pask