ios multiple class implementation - objective-c

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).

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.

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).

Why is there #interface above #implementation?

I am wondering why there is twice #interface. One in class.h and other in class.m. For example:
TestTableViewController.h:
#import <UIKit/UIKit.h>
#interface TestTableViewController : UITableViewController
#end
and (automatically generated) class.m i find:
#import "TestTableViewController.h"
#interface TestTableViewController ()
#end
#implementation TestTableViewController
... methods delegated from UITable delegates
#end
So my question is, what the #interface TestTableViewController () in the .m file is about. Why it is there? Do I need it?
Thanks in advance
The second #interface directive is in the implementation file (.m) -- you can infer from it that it's meant for declaring stuff that the creator of the class didn't want to expose to the user of the class. This usually means private and/or internal methods and properties. Also note that there are two types of doing this. The one (which you see here) is called a "class extension" and it's denoted by an empty pair of parentheses:
#interface MyClass ()
This one is particularily important because you can use this to add additional instance variables to your class.
The second one, called a "category", is indicated by a non-empty pair of parentheses, enclosing the name of the category, like this:
#interface MyClass (CategoryName)
and it's also used to extend the class. You can't add instance variables to a class using categories, but you can have multiple categories for the same class, that's the reason why it's mainly used to extend system/framework classes for which you don't have the source code -- so a category, in this sense, is the exact opposite of the class extension.
The second "interface" defines an extension for the "TestTableViewController" class, which is not visible to someone who only imports the h file. This is the de-facto way for creating private methods in objective C.
In there you can declare private methods and properties that you only want to use in your class, but not expose to other classes.
The interface in the TestTableViewController.h file is the declaration of a class extension. There are 2 round brackets that show this. The syntax is the same as for writing a category for a class. But in this case it's used to declare some sort of private methods the author does not want to expose in the header file
A normal category interface looks like this:
#interface TestTableViewController (Your_Category_Name)
- (void)doSomething;
#end
And the corresponding implementation:
#implementation TestTableViewController (Your_Category_Name)
-(void)doSomething {
// Does something...
}
#end
In your example there is no category name specified, so it just extends the class and you can implement the method in the normal implementation.
Normally this technique is used to "hide" methods. They are not declared in the header file and are not visible if you only import the .h file.

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

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.

Can we not declare methods in the header files?

I am watching the Stanford University iPad and iPhone application Developments course video. The instructor says in the video we can control-drag an UI object to the implementation files to create an action. But in this way the method will not declare in the header file. Does this mean it is ok to implement methods in the .m file but not declare in the .h file?
Depends on how you define "ok" :-)
Objective-C uses dynamic method lookup and does not really enforce access ("private", "public", etc.) specifiers. So you don't need to declare any method in a header file.
However you will end up fighting the compiler as it does do a fair amount of type-checking unless you persuade it not to, and you'll lose by doing so.
You are not required to declare in the header file all methods in the implementation. But if not in the header file obviously you cannot reference them by literal name in another file, nor can you "forward reference" them in the implementation file.
(Note that this is not that different from regular C, but is different from methods of a class in C++.)
It's "OK" to not declare methods in the header yes, under certain circumstances. For instance, if using ARC then the compiler generally needs to know the method signature so it can do the right thing. But basically all it means is that wherever you're using the method, it must already know about the method you're calling.
Since you're talking about Interface Builder, that's slightly different in that it will know about all methods since it can "see" the whole context of your header and implementation files and know that a method exists. i.e. in my terminology above, the method has been defined before it's used.
With regard to defining before use, the general accepted approach is to either:
Define a method in the interface file (.h). e.g.:
MyClass.h
#interface MyClass : NSObject
- (void)someMethod;
#end
MyClass.m
#implementation MyClass
- (void)someMethod {
// do something
}
#end
Define a method in a class continuation category. e.g.:
MyClass.h
#interface MyClass : NSObject
#end
MyClass.m
#interface MyClass ()
- (void)someMethod;
#end
#implementation MyClass
- (void)someMethod {
// do something
}
#end