views:

24

answers:

1

When setting the method of a button call or adding an event listener in objective-c, one normally sets the target to self. However I have a subclass of NSObject named CALLS, separate from the main file. This subclass has a void called METHOD_NAME which should be executed.

THe first question is would the void be +(void)METHOD_NAME

or

-(void)METHOD_NAME in the subclass.

The next is how would I set the target of the addEventListener to use the subclass of NSObject and call the method within it. Would I do

target:[CALLS class];

or create an instance of the subclass of NSObject(calls) and then pass that?

+2  A: 
  • "CALLS" and "METHOD_NAME" are not good names for a class and method. Try to follow the Objective-C conventions. Since you are "nonono", you might call your class something like NNEventListener and the method buttonTapped, for example.

  • First question: it actually doesn't matter. Class methods (+) and instance methods can both be used. However, it would be very unusual to not use an instance method for listening to UI events, so the answer is, use -(void)buttonTapped

  • Second question: I don't think there is a method in all of Cocoa called addEventListener. Where did you hear about that? Have you been using web frameworks to make apps before?

To add a target to a button (or any other UIControl), you use -addTarget:action:forControlEvents: To get a reference to the method that you want to be called, you use the special @selector directive like this:

[aButton addTarget:anObject action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside];

aButton -- your button anObject -- any object. self is just the object that the method belongs to. You can pass in any object at all buttonTapped -- the name of the method that should be called when the button is tapped

Felixyz
yeah, they were just for example, I'm not really using those names.
nonono
thank you, I will try this
nonono
the addEventListener is part of a library
nonono