When to define methods on interface and when not to? - objective-c

I'm using a Objective-C framework for game development called Cocos2d-iphone.
This is how I create a button-graphic in the game:
CCMenuItemImage *battle;
battle = [CCMenuItemImage itemFromNormalImage:#"BattleFightOption1.png" selectedImage:#"BattleFightOption2.png"
target:self selector:#selector(battleFightOption)];
Basically, when the user clicks the button, method battleFightOption runs.
But I wonder, I never did define battleFightOption in the interface.. so, my question is: when is it necessary to define a method in the interface, and when is it not?

In short, every method that is meant to be used from outside the class must be declared in the interface; methods that are internal to the class implementation are omitted. The latter are typically declared in a class extension.

When you use a selector like #selector(methodName:), methodName: is called dynamically at runtime. The compiler doesn't have to know where it is, and doesn't check that the method exists when you compile.
However, it is still a good idea to declare it privately, which is generally done by putting an unnamed category at the top of the .m file (generally referred to as a class extension):
#import "Class.h"
#interface Class ()
- (void)privateMethod;
#end
#implementation Class
...

Anything that you intend to be public, called outside of the class, should be defined in the interface. If you are going to only use #selector(battleFightOption) you really do not need to define the method anywhere but I would recommend that you add a definition in the class extension just as you would any other private method.

Related

overriding undeclared methods in subclass

I have a class with some methods neither declared in .h file nor in any category, I want to override these methods in the subclass to change the behavior slightly. I am thinking of simply redefining those methods in subclass. Is it a good idea? would it even work?
Ideally the subclass needs to know what the methods are if it wants to override the method and still call super.
One way of doing this is by having a separate header file which both the super class and subclass implementations both import.
// MyClass_protected.h
- (void)someMethodThatYouWantSubclassesToBeAbleToOverride;
Then
// MyClass.m
#import "MyClass_protected.h"
// MySubClass.m
#import "MyClass_protected.h"
It'll 'work' in that the compiler allows it. The class that defines these methods probably assumes they do particular things when called, which your implementation needs to respect when overriding them to avoid introducing bugs in the use of the class's interface.
You can override private methods in a base class but the problem is that you can't call [super someMethod]. If you wish to completely replace the original method then this isn't an issue.
Otherwise you need to let the derived class know about the methods in the parent class.

Objective-C – How to hide methods for a class that implements a protocol

Question is in title. Code example:
UIViewController <MyProtocol> *viewcontroller = ...;
[viewcontroller methodFromProtocol]; // I expect to be able to call all methods that the protocol defines
//UIViewControllerSubclass implements MyProtocol
UIViewControllerSubclass *viewControllerSubclassWithoutMyProtocol = [[UIViewControllerSubclass alloc] init];
[viewControllerSubclassWithoutMyProtocol methodThatIsNotInTheInterfaceIsDisplayedHere]; // I only expect to be able to call the methods that are defined in this class' interface even though this class implements MyProtocol
Your question isn't completely clear, but I think you are asking if you can "privately" conform to a protocol?
This can be done by declaring that you conform to the protocol inside the implementation file, rather than the interface file. With view controllers, you can do this in the class continuation that is generated for you automatically in the .m file, otherwise you'll need to add the class continuation in yourself:
#interface MyVCSubclass () <MyProtocol>
Now, any class that imports only the header file will not know your controller conforms to the protocol.
[viewControllerSubclassWithoutMyProtocol methodThatIsNotInTheInterfaceIsDisplayedHere];
I only expect to be able to call the methods that are defined in this class' interface even though this class implements MyProtocol
That's a bad expectation. Objective-C lets you call any method that an object implements. If you try to call a method that an object doesn't implement, two things should happen:
You get a compiler warning (not an error though)
When the code runs, it crashes, unless you've taken steps to handle such an event.
If a class implements a protocol but doesn't declare that it does so in a public header, then you can still call the method (since Objective C doesn't have private methods). I'd have thought you'd get a compiler warning, but if you're calling this from a file within the same Xcode project as your object (that is, you're not building a static library) then it's possible that Xcode is getting smart and deciding that since the method exists, it must be OK to call.
It wasn't clear from your question what you expected to happen and what actually happened. If you supply that information, we'll be able to give better answers.

Guidelines for declaring methods in #interface, in an extension, or not declaring at all

I've been learning Object Oriented Programming in Objective-C and I'm a little confused about method declaration and implementation.
In some lectures I've been studying, the professor declares public methods in the .h file and then implements them in the .m file; or he may declare them private in the .m file and them implement them in the #implementation ClassViewController section.
Sometimes, however, he doesn't declare methods at all and just skips to method implementation in the #implementation ClassViewController section.
How do I make this distinction where to declare something either public or private, or not having to declare anything at all?
Methods should be declared publicly when you want that method to be accessible to outside classes, and privately otherwise. A method that was declared in a superclass does not need to be declared again in it's subclasses if you override it. As far as methods that are implemented without any previous declaration, that method can still be called, but it is only 'visible' to methods below it in the file, and will throw a warning otherwise. As such, this is rarely done (it is declared privately instead), with the exception of if that method is intended to be the target of an #selector.
The short answer is that all methods should be declared (either publicly or privately).
But I suspect what you actually saw your professor do was override a method that was already declared in a superclass.
So for example, if you wanted to override viewDidLoad in your CustomViewController, you would not declare viewDidLoad again, because that method was already declared in the header for UIViewController (the superclass).
You would simply go to the implementation of your subclass and write your implementation of viewDidLoad which would override the one you inherited. If you go watch the lecture again, I'm guessing that is what you saw.

Interface is declared twice? - Objective-C

I'm new to Objective-C and am looking through many examples to wrap my head around it.
I came across this code:
#interface ImagePickerHelper : NSObject <UIImagePickerControllerDelegate, UIPopoverControllerDelegate, UINavigationControllerDelegate>
//Blah Blah
#end
#interface ImagePickerHelper ()
//Blah Blah
#end
On googling, I came to know that they specify the superclass and delegates (about which, incidentally, I know zilch) after the interface name.
But why is the interface declared twice here?
No, it is not declared two times, it is a Class interface (an anonymous category) that it is created to hold methods that you want to keep private in your class, for methods that you don't want other class to see or to interact with ..
People often declare a standard category with a name(usually "private") to hold private methods, but
the main advantage of using an anonymous category over a named category is that the compiler will complain if you do not implement a method declared in the anonymous category.
I have noticed that it is created by default from XCode 4.3 onwards .
Putting methods into this extension Class it is like declaring private methods in Java or C++ ...
The second "#interface" you see (probably in a .m file) is a class extension, and probably meant for private methods (well, private in the sense that the compiler will generate "may not respond to" warnings).

Class extension vs class category

Class extensions #interface Class () are a lot more powerful and can inject variables into the class. Categories #interface Class (Category) can't.
What other differences are there, and when should one use a category over a class extension?
The main difference is that with an extension, the compiler will expect you to implement the methods within your main #implementation, whereas with a category you have a separate #implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally) -- it's meant to be just that, an extension.
A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension). The methods declared by a class extension are implemented in the #implementation block for the original class so you can’t, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString.
The syntax to declare a class extension is similar to the syntax for a category, and looks like this:
#interface ClassName ()
#end
Because no name is given in the parentheses, class extensions are often referred to as anonymous categories.
Unlike regular categories, a class extension can add its own properties and instance variables to a class. If you declare a property in a class extension, like this:
#interface XYZAnimal () {
id _someCustomInstanceVariable;
}
...
#end
IMHO, it's best to think of class extensions as private interface to a class. The primary interface (in your .h file) acts as the public interface which defines the class's behavioural contract with other classes.
Use class extensions to Hide Private Information
Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class itself. It’s common, for example, to define a property as readonly in the interface, but as readwrite in a class extension declared above the implementation, in order that the internal methods of the class can change the property value directly.
As an example, the XYZPerson class might add a property called uniqueIdentifier, designed to keep track of information like a Social Security Number in the US.
It usually requires a large amount of paperwork to have a unique identifier assigned to an individual in the real world, so the XYZPerson class interface might declare this property as readonly, and provide some method that requests an identifier be assigned, like this:
#interface XYZPerson : NSObject
...
#property (readonly) NSString *uniqueIdentifier;
- (void)assignUniqueIdentifier;
#end
In order for the XYZPerson class to be able to change the property internally, it makes sense to redeclare the property in a class extension that’s defined at the top of the implementation file for the class:
#property (readwrite) NSString *uniqueIdentifier;
Note: The readwrite attribute is optional, because it’s the default. You may like to use it when redeclaring a property, for clarity.
Categories are an Objective-C language feature that let you add new methods to an existing class. Extensions are a special case of categories that let you define methods that must be implemented in the main implementation block.
Private declarations can be in class extensions, which mainly are some properties, because we have no need to declare a method before we call it.
ios extension similiar to c#,java abstract class or interface
ios category similiar to c# class extension