When do you create initialization methods in .m files using class extension? - objective-c

I was going through one of Apple's tutorial (your second iOS app). Basically, you have a primary data class and a data controller class. Controller class manipulates the primary data objects by creating an array that holds them.
Suddenly this pops up:
"...But the “create the master collection” task is a task that only the data controller object needs to know about. Because this method does not need to be exposed to other objects, you do not need to declare it in the header file."
And turns out the initialization of the "master collection" appears in the .m file as a class extension instead of the header file. Why do we want to do this? What's wrong with declaring the method of initialization within the header file directly?
Header file of the data controller:
#import <Foundation/Foundation.h>
#class BirdSighting;
#interface BirdsSightingDataController : NSObject
#property (nonatomic, copy) NSMutableArray *masterBirdSightingList;
- (NSUInteger)countOfList;
- (BirdSighting *)objectInListAtIndex:(NSUInteger)theIndex;
- (void)addBirdSightingWithName:(NSString *)inputBirdName location:(NSString *)inputLocation;
#end
this is the corresponding .m file:
#import "BirdsSightingDataController.h"
#import "BirdSighting.h"
#interface BirdsSightingDataController ()
- (void)initializeDefaultDataList; //class extension
#end
#implementation BirdsSightingDataController
...

Putting methods in an interface inside of a .m file is the proper way of making methods hidden.
-
There's nothing really "wrong" with declaring this method in the header file. You can do this if you want.
However, it's better practice to hide methods in your implementation file by using private header extensions if there's no need to make the method public. This means that if no other class needs to call this method, or if no other programmer needs to call this method, then it's better practice to keep the method private, or hidden.
A case like this will help explain the situation:
First, putting methods in a hidden interface extension in your .m files is a conscious decision. As another developer, if I am looking at your code and see that you have consciously decided to put a method in a hidden interface () in your implementation file, I will know that this method is used only in this class... and that YOU have done this on purpose.
Furthermore, it is good practice because if you are developing an API which is going to be used by other people, or working on the same code base with other developers, it limits their ability to call specific methods outside of the class itself. That means, they can't accidentally call the method from another object.

Related

Questions on creating an empty template class just for the purpose of subclassing

I am trying to create a plugin system within my objective-c project so I can just create a class that follows certain convention and it would work right out of the box.
These classes contain common headers (which includes protocols and categories), and also needs to follow the included protocols. But other than that each class is very distinct and don't share any code.
I don't want to have to write the same lines every time I need to write a plugin so thought about creating a base class like this:
#import <Foundation/Foundation.h>
#import "Helper.h"
#import "ComponentProtocol.h"
#import "UIView+Extension.h"
#interface Component : NSObject <ComponentProtocol>
+ (UIView *)someProtocolFunction;
#end
The class has NO implementation
And then whenever I need to create one of these classes I would just create a class that looks like this:
#import "Component.h"
#interface CustomComponent : Component
#end
So I have two questions:
Is this an OK thing to do? The base class won't have a single line of code in it since I'm just using it as a template. Or if there's a better way to do this?
As you can see in the code, the protocol requires a class method. I don't know how I would go about this in the subclasses. If it was an instance method I could just call [super someProtocolFunction]; and then add the subclass-specific logic, but I don't know how this would work in a class method setting.

What is the purpose of a class extension without any content?

According to developer documentation, a class extension is implemented by declaring an #interface in the implementation file, and it can also be used to redeclare instance variables to be private. However, I frequently see the code below that does not declare new methods or instance variables. What is its purpose?
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
...
There is no purpose behind such code. The only reason it is there is that it is part of the standard template for creating .m files in Xcode.
With this said, such class extensions are entirely harmless, so keeping them in case you need to add private methods or variables does not hurt performance of your app. In the end, it is a matter of personal taste: for example, I remove such unused template-generated artifacts from my code, but I can accept an argument in favor of keeping them as well.
If you do not wish to have these class extensions generated by default, clone and modify Xcode template for new Objective-C classes (here is a Q&A explaining how to do it).

Multiple #interface declarations generated by Xcode for NSViewController?

I am making a Cocoa application, and using Xcode for various code-generation. Works fine for generating .h and .m files for subclassing UIView, but when i subclass UIViewController i get an #interface declaration identical in both files, except that in the .m file it has ( ) at the end:
//in MyViewController.h
#interface MyViewController : NSViewController <MyViewDelegate>
#end
but also
//in MyViewController.m
#interface MyViewController ()
#end
#implementation MyViewController
#end
Yet it compiles fine. So, assuming this is normal behavior, the two-parts of question are:
(A) Why does this happen, and
(B) What are the results -- especially in terms of compile order?
Thanks!
when i subclass UIViewController i get an #interface declaration identical in both files, except that in the .m file it has ( )
As you noticed, the two interface blocks are not identical -- the () is important. The one with the () is a class extension, which is similar to a category without a name. The two important differences between a category and a class extension are:
You can declare instance variables in a class extension, but you can't in a category.
A class extension must appear in the same file as the implementation block.
Class extensions are useful for declaring instance variables and methods that you don't want to expose in the header file, such as methods or variables that are specific to the implementation and shouldn't be relied upon by users of the class.
Are you familiar with Categories? What you are observing is similar, but has important distinctions from Categories. The distinction here is that it is anonymous (hence the empty parens) and compiled at the same time the original class is compiled. That later part is an important part: it means you can add instance properties (storage). This is most commonly used to declare "internal only" or "private" methods and properties. But keep in mind that at runtime there is no notion of 'private' enforcement, it's all about what interface you have published vs. not published. This is just one way to have very clearly defined interface that is only 'published' to people who author the implementation file of the core class.

Objective-C #interface and #implementation clarification

I'm still fairly new to Objective-C but I'd love to learn more about how it should be done.
I'm building a simple cheat sheet that I'd like to print and put on my office wall as a reminder.
Here's what I have so far:
// Headers (.h)
// Shows what's available to other classes
#interface ExampleViewController : UIViewController
// Declare public methods, ivars &
// properties that are synthesized.
#end
// Implementation (.m)
// Defines the content of the class
#interface ExampleViewController ()
// Class extension allowing to declare
// private methods, ivars & properties that are synthesized.
#end
#implementation ExampleViewController
// Private Properties
// Method definitions
#end
One thing I don't understand is why have both #interface and #implementation inside the implementation .m file?
I get that we can declare private stuff but why not simply throw them in #implementation like:
#implementation ExampleViewController
UIView *view; // private property
- (void)...more code
#end
#1 - Why should I ever use #interface from within my implementation .m file?
#2 - For header .h, why should I ever use #class more than #import?
#import actually gets the whole definition and #class tells the compiler that the symbol is a class. So I just don't see why I should ever use #class?
#3 - Otherwise, is there anything I should be adding somewhere in my .h or .m cheat sheet?
That's not a problem-related question but a more wiki-esque question so we everybody can look it up and completely and quickly understand those concepts as they are very hard to grasp for any newcomer.
Why should I ever use #interface from within my implementation .m file?
Because it's better to clearly separate public and private parts of the class.
For header .h, why should I ever use #class more than #import?
When forward-declaring classes for use in protocols. Like this:
#class Foo;
#protocol FooDelegate
// this wouldn't compile without a forward declaration of `Foo'
- (void)fooDidFinishAction:(Foo *)f;
#end
Otherwise, is there anything I should be adding somewhere in my .h or .m cheat sheet?
That's way too general to be answered in one post.
1 - Why should I ever use #interface from within my implementation .m file?
When you do not intend to expose that interface to any other component. That's certainly the case for private class extensions but may also apply for something like a test which doesn't need a .h file at all because while it does define a class it does not need to expose an interface for any other component to use.
2 - For header .h, why should I ever use #class more than #import?
Invert your question; why should I ever use #import rather than #class?
#class informs the compiler that a class definition of that name will exist to be linked but says nothing about it's interface.
#import makes the class' interface available to you.
A forward declaration requires less work and can allow for faster builds. It is also not always possible to #import a class at all times (as in circular references like #H2CO3's protocol example). If all you need to know is that a class exists then just use the forward declaration. When you actually need to interact with its specific interface (usually in your class' implementation) then you need to #import.
3 - Otherwise, is there anything I should be adding somewhere in my .h or .m cheat sheet?
Unless you intend to actually expose ivars as a public interface (almost certainly not the case) leave them out of your .h and expose only properties instead.
Keep your public interface as simple as possible. Try not to reveal implementation details. However keep it informative enough that users of the class can verify its behavior using that public interface. (I find test driving the design of the class using only it's public interface a good tool for striking this balance.)
Imports and forward declarations expose dependencies. Keep them to the minimum you actually need so that you can understand what the class in question actually depends on.
Delegate protocols and block types are a common part of a class' interface but not part of the #interface. Include them in the .h if they are needed by other classes (e.g. to register callbacks).

ios multiple class implementation

I came from front-end development, so MVC and OOP still give me some head shakes. Just to explain to you I send like 500 dicionaries (with 100 parameters) to a nodejs server. The problem is that I has creating ivars for each parameter and each dicionary. Now I want to create some classes like a person class, in the same header file that I have my syncronization class for example. I can make something like this on the header:
#import <Foundation/Foundation.h>
#import "GCDAsyncSocket.h"
#class GCDAsyncSocket;
#interface socketDelegate : NSObject<NSStreamDelegate>
{
NSInputStream *inputStream;
NSOutputStream *outputStream;
NSMutableArray *messages;
GCDAsyncSocket *socket;
dispatch_queue_t connectionQueue_;
}
- (void) initNetworkCommunication;
- (void) sendMessage:(NSArray *)message:(int)numberOfContactsToSend;
#end
#interface personInfo: NSObject
#property (nonatomic,weak)NSString*firstName;
#property (nonatomic,weak)NSString*lastName;
#property (nonatomic,weak)NSDictionary*dicToSendWithConctactInfo;
#end
But in the implementation I don't know how to handle the multiple classes. Like I've a method inside the "socketDelegate" class that needs to use the person class, but it's not available inside it.
What's the best way to implement this?
To answer your immediate question, you can just forward-declare personInfo at the top of the file before socketDelegate:
#class personInfo;
Usually you just put each public class in its own implementation and header files, and each implementation file includes the header files of all the classes it uses. The header files usually just need to forward declare the classes they refer to (as you are doing with #class GCDAsyncSocket;. However, it doesn't make sense that you are both importing #import "GCDAsyncSocket.h" and forward-declaring. From what you are using it for here, you don't need the import. However, to properly use GCDAsyncSocket, you will need to implement GCDAsyncSocketDelegate protocol, which will require you to import the header; however, you should probably implement that protocol as part of a "class extension" inside the implementation file).
You only need to import the header of something in your header if you are subclassing a class, or implementing a protocol that is declared in the header. For all other uses (i.e. using the class or protocol as part of a pointer type), you can simply forward-declare it. (And for implementing a protocol, you can do that in the implementation file with a "class extension" if you don't need people to know you're implementing the protocol.
Different classes should, typically, be in different files. Once PersonInfo (please capitalize class names) has it's own PersonInfo.h and PersonInfo.m, then you simply add
#import "PersonInfo.h"
to the header file above to be able to reference PersonInfo from your SocketDelegate class (again, please capitalize class names).