views:

114

answers:

4

Hi,

I am working on a class A which has a method -(void)DoSmthing1. I am making a call to another method-(void)DoSmthing2 in class B. Now after doing some operations in class B, the method is supposed to call back a method-(void)DoSmthing3 previous class.

How will i call a method of current class from another class?? Can someone please help me....

Thanks in advance

edit1:: My Code: Class A

{
-(void) MethodA {

}

-(void) MethodB {
   ClassB *clsB = [[ClassB alloc] init];
   [clsB MethodC];
}  
}  

Class B

{
  -(void)MethodC:(selector) {
  //here i want to call MethodA of classA, and i will prefer if it is possible by sending the name of the method as selector in this method(methodC)

    }  
}

edit2::

Another example i want to do smthing like follwoing:

ClassB *b = [[ClassB alloc] nitWithTarget:self selector:@selector(methodfromClassA) object:nil];

Here i want to call a method of class A once some task in Class B is completed, and that too from class A.

I hope it is much clear now.

Edit3:

- (void)loadView {
    AsyncConnection *async =[[AsyncConnection alloc] init];
    [async getAsync:self callback:@selector(test1)];
}

above code is from first class

-(void)getAsync:(id)anObject callback:(SEL)selector {
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:anObject 
                                                                            selector:@selector(selector) 
                                                                              object:nil];
    [queue addOperation:operation];
    [operation release];

}

and above code is from second class. Here i want to call a method of first class which is passed as selector.

+2  A: 

It sounds like you would benefit from reading the introductory material: The Objective-C Programming Language and Cocoa Fundamentals Guide. Additionally, you should read up on the basics of object-oriented programming (there are dozens of overviews all over the web and Amazon).

Essentially, you're confusing a class (the blueprint for creating an object, in its most basic description) and an instance of a class (an actual "instantiated" object of a given class). Somewhere you're going to have to have a reference from one instance to another (like objectB = [[ClassB alloc] init]) to send a message (like [objectB doSomethingAnObjectOfClassBWouldDo]). You might accomplish this by storing the reference as an instance variable or inside a collection (array, dictionary, etc.) that is an instance variable of the class that needs to "remember" who it needs to talk to.

It's important to realize you're trying to walk before you've learned to crawl with this platform. The only cure is to study. A lot. Guided books help.

Joshua Nozzi
may b u didnt get me, i have added the sample code in my original post. can u plz check that...
pankaj
If you're looking for a target/action style interaction, then your ClassB should have an instance variable of type SEL and one of type id. If you're looking for ClassB to occasionally ask ClassA something it needs to know, consider using the delegate approach. Both are addressed in the introductory material. If you need more detail, you'll have to post more detail. Using vague terms doesn't help: EXACTLY WHAT DO YOU WANT TO DO? Give context as it relates to your actual project so we know what to suggest.
Joshua Nozzi
i want to the first thing that you specified,i.e, looking for a target/action style interaction.
pankaj
can u pls give me some sample code helping me how to achieve it
pankaj
No, because you haven't described exactly what you're trying to do. It's unreasonable to expect people to hand you source code when you can't fully describe your goal.
Joshua Nozzi
please check my third edit
pankaj
Wait, if instance of ClassA calls instance of ClassB's -getAsync:callback: method, wouldn't you be passing the ClassA instance in, therefore creating an NSInvocationOperation with ClassA instance and its selector? That's what your code is doing. Isn't that what you want?
Joshua Nozzi
yes, this what i am intending to do but i am getting exc bad access when the debugger tries to allocate NSInvocationOperation with selector from class A. I can check in debugger that i am getting both object and selector as parameter but still it is not working.
pankaj
Seems bbum's answer contains the reason: "@selector(someSelector)" should be just "someSelector".
Joshua Nozzi
That wouldn't cause an `EXC_BAD_ACCESS`. At any rate, you're right: pankaj, you need to read up on object-oriented programming. Classes are not merely groups of methods; they are blueprints for objects, which send messages to each other. Understanding that and the many patterns described in the CFG (target-action is but one of them) will lead you to the answer to your question, and all that will remain will be to write the code.
Peter Hosey
My head hurts...
Joshua Nozzi
My apologies for not being able to clarify the question.It probably happened because i made extra effort in explaining my problem. From next time i will try to stick to point. Thanks anyways you tried to help me.
pankaj
+1  A: 

Then new approach: Should be something like:

classB.h

classA *aObj;

@property(nonatomic, retain) classA *aObj;

classB.m

@synthetize aObj;

classA.m

// after init class b obj

[bOjb setAObj:self];

classB.m

[aObj whateverMethodOfClassA];

Let me know if not clear.

My sugestion, is that generally if you want to avoid a real mess and a nightmare to debug, you should use observers and notifications rather than this kind of cross methods calls.

Make class A an observer of a notification of class B:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(classA-method-name:) name:@"notification-name" object:class-B-object ];

And when ready in class-B notify class A with parms:

[[NSNotificationCenter defaultCenter] postNotificationName:@"notification-name" object:self];

Just an idea.

Martha
I'm not sure this is necessarily better than just sending a message. It creates the same coupling, but with notifications, it's hidden and indirect. This post from the creator of NetNewsWire explains the trouble notifications can be: http://inessential.com/2007/04/25/thoughts_about_large_cocoa_projects
Chuck
hi martha, thanks for the great suggestion but i am working on a class which will be reused as a template and i have to do it by using the selectors. can u help me in that? u can check what i am doing in my edit3
pankaj
Then you have two ways:
Martha
A: 

One option is to use the delegate pattern in Objective C. Have the object of class A pass itself to an object of class B to be the handler for certain methods.

hotpaw2
+1  A: 
- (void)loadView {
    AsyncConnection *async =[[AsyncConnection alloc] init];
    [async getAsync:self callback:@selector(test1)];
}

Other class:

-(void)getAsync:(id)anObject callback:(SEL)selector {
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
         initWithTarget:anObject 
               selector:@selector(selector)
                 object:nil];

    [queue addOperation:operation];
    [operation release];

}

First, if you want to use the above pattern, remove the @selector() from @selector(selector). You already have the selector. Doing @selector(selector) will create the SEL named selector and not the selector passed in as the argument.

Next, this seems like an odd pattern to start with; it'll work, but any experienced Obj-C/iOS/Cocoa developer will get the willies looking at it. Since you wrote the AsyncConnection class, use the delegate pattern. I.e. in the class that implements loadView.

That is, in AsyncConnection.h:

@property(retain) ClassA *callbackHandler;

And then:

- (void)loadView {
    AsyncConnection *async =[[AsyncConnection alloc] init];
    [async setCallbackHandler: self];
}

Then, in AsyncConnection, you would refer to the callback handler directly as self.callbackHandler (or [self callbackHandler]).

bbum
"any experienced Obj-C/iOS/Cocoa developer will get the willies looking at it." More than that, a reasonably experienced one got thoroughly confused just trying to figure out the goal. :-)
Joshua Nozzi
Is there a reason for `callbackHandler` to be an owning relationship? Seems like that would have the connection and the object that creates the connection owning each other.
Peter Hosey
Personal habit; I generally use `retain` and have a clean-up/invalidation/kiss-of-death mechanism to avoid having dangling pointers. Debugging bloat is much easier than dangling pointer crashes.
bbum
thanks bbum you are life saver for me. You pointed my mistake and it is working fine for me. Till now i was just using selector in uibuttons and so had limited knowledge about them but now my concept about selector is much clearer. Thanks again
pankaj
Awesome. Happy to help. Good luck!
bbum