Does #interface with properties only require #implementation? - objective-c

I would like to define a C struct-like in my Objective-C header file which includes _ivars only, however, since this a header file only there would be no corresponding #implementation. Is that even possible?
(I also don't want to force the header file includers to add #implementation since this is a simple descriptor definition)
I would like it to be #interface definition so users who like to extend it and add more data members to it could do so (again, only _ivars). However, other suggestions might work if you think of something.

Yes, there has to be an #implementation declared for the class that is compiled by the compiler to cause the class to be realized at runtime (including the storage backing the #property declarations.
Once compiled, that class cannot extended with additional #properties that are automatically backed (it can be extended via categories, but you're on your own for storage and categorical extensions of classes is generally not recommended anyway).

Related

Objective-C "class prototyping" [duplicate]

I'm writing a multiview app that utilizes a class called RootViewController to switch between views.
In my MyAppDelegate header, I create an instance of the RootViewController called rootViewController. I've seen examples of such where the #class directive is used as a "forward class declaration," but I'm not quite sure what this means or accomplishes.
#import <UIKit/UIKit.h>
#class RootViewController;
#interface MyAppDelegate
.
.
.
It basically tells the compiler that the class RootViewController exists, without specifying what exactly it looks like (ie: its methods, properties, etc). You can use this to write code that includes RootViewController member variables without having to include the full class declaration.
This is particularly useful in resolving circular dependencies - for example, where say ClassA has a member of type ClassB*, and ClassB has a member of type ClassA*. You need to have ClassB declared before you can use it in ClassA, but you also need ClassA declared before you can use it in ClassB. Forward declarations allow you to overcome this by saying to ClassA that ClassB exists, without having to actually specify ClassB's complete specification.
Another reason you tend to find lots of forward declarations is some people adopt a convention of forward declaring classes unless they absolutely must include the full declaration. I don't entirely recall, but possibly that's something that Apple recommends in it's Objective-C guiding style guidlines.
Continuing my above example, if your declarations of ClassA and ClassB are in the files ClassA.h and ClassB.h respectively, you'd need to #import whichever one to use its declaration in the other class. Using forward declaration means you don't need the #import, which makes the code prettier (particularly once you start collecting quite a few classes, each of which would need an `#import where it's used), and increases compiling performance by minimising the amount of code the compiler needs to consider while compiling any given file.
As an aside, although the question is concerned solely with forward declarations in Objective-C, all the proceeding comments also apply equally to coding in C and C++ (and probably many other languages), which also support forward declaration and typically use it for the same purposes.
Forward declarations are mainly to avoid circular imports, where one file imports another file which imports the first file etc. Basically when you import a file, contents of the file are substituted at the point of import when you build your project, which is then fed to the compiler. If you have circular imports, you'd have an infinite loop which would never compile. Fortunately xcode will tell you about this before trying. The forward declaration says "Don't import this class but just know that it exists. " Without either an import or a forward declaration, you get an error that no such class exists.
#class or forward class declaration(incomplete type) - just tell to a compiler that this class exists. In this case the compiler does not know anything about type memory layout - class size, members, or methods. That is why you can only use for defining classes via references and pointers.
Advantages:
reduce build time
break cyclic references

Why are objective-c #interface definitions placed in a seperate .h file?

I recognize that this is a general type of question but I'd be interested in your opinion on:
why are #interface #protocol and #property definitons seperated into a .h header file and then imported into the implementation file?
Is there anybody out there who just defines everything in a .m file?
BTW> its not that I am planning on not using .h files, just trying to understand the thinking behind it!
Because Objective-C relies on standard C infrastructure in which every compilation unit (.m) is compiled separately and then all of them are linked together.
This means that the static type checking phase of the Objective-C compiler will need just the .h files to know the characteristics of declared classes (eg. signatures of methods) but just to ensure that everything is used as it is supposed to be, and this is why you #import them in other source files that require what you declared inside the header.
if you have A.h/.m and B.h/.m which uses A you can think of the header file like a contract: "if you want to use A, I will link its binary code at the end of the compilation phase, what A is able to provide is described in this header file and this is the only thing you should know"

Objective-C: Forward Class Declaration

I'm writing a multiview app that utilizes a class called RootViewController to switch between views.
In my MyAppDelegate header, I create an instance of the RootViewController called rootViewController. I've seen examples of such where the #class directive is used as a "forward class declaration," but I'm not quite sure what this means or accomplishes.
#import <UIKit/UIKit.h>
#class RootViewController;
#interface MyAppDelegate
.
.
.
It basically tells the compiler that the class RootViewController exists, without specifying what exactly it looks like (ie: its methods, properties, etc). You can use this to write code that includes RootViewController member variables without having to include the full class declaration.
This is particularly useful in resolving circular dependencies - for example, where say ClassA has a member of type ClassB*, and ClassB has a member of type ClassA*. You need to have ClassB declared before you can use it in ClassA, but you also need ClassA declared before you can use it in ClassB. Forward declarations allow you to overcome this by saying to ClassA that ClassB exists, without having to actually specify ClassB's complete specification.
Another reason you tend to find lots of forward declarations is some people adopt a convention of forward declaring classes unless they absolutely must include the full declaration. I don't entirely recall, but possibly that's something that Apple recommends in it's Objective-C guiding style guidlines.
Continuing my above example, if your declarations of ClassA and ClassB are in the files ClassA.h and ClassB.h respectively, you'd need to #import whichever one to use its declaration in the other class. Using forward declaration means you don't need the #import, which makes the code prettier (particularly once you start collecting quite a few classes, each of which would need an `#import where it's used), and increases compiling performance by minimising the amount of code the compiler needs to consider while compiling any given file.
As an aside, although the question is concerned solely with forward declarations in Objective-C, all the proceeding comments also apply equally to coding in C and C++ (and probably many other languages), which also support forward declaration and typically use it for the same purposes.
Forward declarations are mainly to avoid circular imports, where one file imports another file which imports the first file etc. Basically when you import a file, contents of the file are substituted at the point of import when you build your project, which is then fed to the compiler. If you have circular imports, you'd have an infinite loop which would never compile. Fortunately xcode will tell you about this before trying. The forward declaration says "Don't import this class but just know that it exists. " Without either an import or a forward declaration, you get an error that no such class exists.
#class or forward class declaration(incomplete type) - just tell to a compiler that this class exists. In this case the compiler does not know anything about type memory layout - class size, members, or methods. That is why you can only use for defining classes via references and pointers.
Advantages:
reduce build time
break cyclic references

Minutia on Objective-C Categories and Extensions

I learned something new while trying to figure out why my readwrite property declared in a private Category wasn't generating a setter. It was because my Category was named:
// .m
#interface MyClass (private)
#property (readwrite, copy) NSArray* myProperty;
#end
Changing it to:
// .m
#interface MyClass ()
#property (readwrite, copy) NSArray* myProperty;
#end
and my setter is synthesized. I now know that Class Extension is not just another name for an anonymous Category. Leaving a Category unnamed causes it to morph into a different beast: one that now gives compile-time method implementation enforcement and allows you to add ivars. I now understand the general philosophies underlying each of these: Categories are generally used to add methods to any class at runtime, and Class Extensions are generally used to enforce private API implementation and add ivars. I accept this.
But there are trifles that confuse me. First, at a hight level: Why differentiate like this? These concepts seem like similar ideas that can't decide if they are the same, or different concepts. If they are the same, I would expect the exact same things to be possible using a Category with no name as is with a named Category (which they are not). If they are different, (which they are) I would expect a greater syntactical disparity between the two. It seems odd to say, "Oh, by the way, to implement a Class Extension, just write a Category, but leave out the name. It magically changes."
Second, on the topic of compile time enforcement: If you can't add properties in a named Category, why does doing so convince the compiler that you did just that? To clarify, I'll illustrate with my example. I can declare a readonly property in the header file:
// .h
#interface MyClass : NSObject
#property (readonly, copy) NSString* myString;
#end
Now, I want to head over to the implementation file and give myself private readwrite access to the property. If I do it correctly:
// .m
#interface MyClass ()
#property (readwrite, copy) NSString* myString;
#end
I get a warning when I don't synthesize, and when I do, I can set the property and everything is peachy. But, frustratingly, if I happen to be slightly misguided about the difference between Category and Class Extension and I try:
// .m
#interface MyClass (private)
#property (readwrite, copy) NSString* myString;
#end
The compiler is completely pacified into thinking that the property is readwrite. I get no warning, and not even the nice compile error "Object cannot be set - either readonly property or no setter found" upon setting myString that I would had I not declared the readwrite property in the Category. I just get the "Does not respond to selector" exception at runtime. If adding ivars and properties is not supported by (named) Categories, is it too much to ask that the compiler play by the same rules? Am I missing some grand design philosophy?
Class extensions were added in Objective-C 2.0 to solve two specific problems:
Allow an object to have a "private" interface that is checked by the compiler.
Allow publicly-readable, privately-writable properties.
Private Interface
Before Objective-C 2.0, if a developer wanted to have a set of methods in Objective-C, they often declared a "Private" category in the class's implementation file:
#interface MyClass (Private)
- (id)awesomePrivateMethod;
#end
However, these private methods were often mixed into the class's #implementation block (not a separate #implementation block for the Private category). And why not? These aren't really extensions to the class; they just make up for the lack of public/private restrictions in Objective-C categories.
The problem is that Objective-C compilers assume that methods declared in a category will be implemented elsewhere, so they don't check to make sure the methods are implemented. Thus, a developer could declare awesomePrivateMethod but fail to implement it, and the compiler wouldn't warn them of the problem. That is the problem you noticed: in a category, you can declare a property (or a method) but fail to get a warning if you never actually implement it -- that's because the compiler expects it to be implemented "somewhere" (most likely, in another compilation unit independent of this one).
Enter class extensions. Methods declared in a class extension are assumed to be implemented in the main #implementation block; if they're not, the compiler will issue a warning.
Publicly-Readable, Privately-Writeable Properties
It is often beneficial to implement an immutable data structure -- that is, one in which outside code can't use a setter to modify the object's state. However, it can still be nice to have a writable property for internal use. Class extensions allow that: in the public interface, a developer can declare a property to be read-only, but then declare it to be writable in the class extension. To outside code, the property will be read-only, but a setter can be used internally.
So Why Can't I Declare a Writable Property in a Category?
Categories cannot add instance variables. A setter often requires some sort of backing storage. It was decided that allowing a category to declare a property that likely required a backing store was A Bad Thing™. Hence, a category cannot declare a writable property.
They Look Similar, But Are Different
The confusion lies in the idea that a class extension is just an "unnamed category". The syntax is similar and implies this idea; I imagine it was just chosen because it was familiar to Objective-C programmers and, in some ways, class extensions are like categories. They are alike in that both features allow you to add methods (and properties) to an existing class, but they serve different purposes and thus allow different behaviors.
You're confused by the syntactic similarity. A class extension is not just an unnamed category. A class extension is a way to make part of your interface private and part public — both are treated as part of the class's interface declaration. Being part of the class's interface, an extension must be defined as part of the class.
A category, on the other hand, is a way of adding methods to an existing class at runtime. This could be, for example, in a separate bundle that is only loaded on Thursdays.
For most of Objective-C's history, it was impossible to add instance variables to a class at runtime, when categories are loaded. This has been worked around very recently in the new runtime, but the language still shows the scars of its fragile base classes. One of these is that the language doesn't support categories adding instance variables. You'll have to write out the getters and setters yourself, old-school style.
Instance variables in categories are somewhat tricky, too. Since they aren't necessarily present when the instance is created and the initializer may not know anything about them, initializing them is a problem that doesn't exist with normal instance variables.
You can add a property in a category, you just can't synthesize it. If you use a category, you will not get a compile warning because it expects the setter to be implemented in the category.
Just a little clarification about the REASON for the different behavior of unnamed categories (now known as Class Extensions) and normal (named) categories.
The thing is very simple. You can have MANY categories extending the same class, loaded at runtime, without the compiler and linker ever knowing. (consider the many beautiful extensions people wrote to NSObject, that add it functionality post-hoc).
Now Objective-C has no concept of NAME SPACE. Therefore, having iVars defined in a named category could create a symbol clash in runtime. If two different categories would be able to define the same
#interface myObject (extensionA) {
NSString *myPrivateName;
}
#end
#interface myObject (extensionB) {
NSString *myPrivateName;
}
#end
then at the very least, there will be memory overrun at runtime.
In contradiction, Class extensions have NO NAME, and thus there can be only ONE. That's why you can define iVars there. They are assured to be unique.
As for the compiler errors and warnings related to categories and class extensions + ivars and property definitions, I have to agree they are not so helpful, and I spent too much time trying to understand why things compile or not, and how they work (if they work) after they compile.

#class vs. #import

It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header to avoid any circular inclusions. I also understand that an #import is a simple ifndef so that an include only happens once.
My inquiry is this: When does one use #import and when does one use #class? Sometimes if I use a #class declaration, I see a common compiler warning such as the following:
warning: receiver 'FooController' is a forward class and corresponding #interface may not exist.
Would really love to understand this, versus just removing the #class forward-declaration and throwing an #import in to silence the warnings the compiler is giving me.
If you see this warning:
warning: receiver 'MyCoolClass' is a forward class and corresponding #interface may not exist
you need to #import the file, but you can do that in your implementation file (.m), and use the #class declaration in your header file.
#class does not (usually) remove the need to #import files, it just moves the requirement down closer to where the information is useful.
For Example
If you say #class MyCoolClass, the compiler knows that it may see something like:
MyCoolClass *myObject;
It doesn't have to worry about anything other than MyCoolClass is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, #class suffices 90% of the time.
However, if you ever need to create or access myObject's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "MyCoolClass.h", to tell the compiler additional information beyond just "this is a class".
Three simple rules:
Only #import the super class, and adopted protocols, in header files (.h files).
#import all classes, and protocols, you send messages to in implementation (.m files).
Forward declarations for everything else.
If you do forward declaration in the implementation files, then you probably do something wrong.
Look at the Objective-C Programming Language documentation on ADC
Under the section on Defining a Class | Class Interface it describes why this is done:
The #class directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name. Being simple, it avoids potential problems that may come with importing files that import still other files. For example, if one class declares a statically typed instance variable of another class, and their two interface files import each other, neither class may compile correctly.
Use a forward declaration in the header file if needed, and #import the header files for any classes you're using in the implementation. In other words, you always #import the files you're using in your implementation, and if you need to reference a class in your header file use a forward declaration as well.
The exception to this is that you should #import a class or formal protocol you're inheriting from in your header file (in which case you wouldn't need to import it in the implementation).
The common practice is using #class in header files (but you still need to #import the superclass), and #import in implementation files. This will avoid any circular inclusions, and it just works.
Another advantage: Quick compilation
If you include a header file, any change in it causes the current file also to compile but this is not the case if the class name is included as #class name. Of course you will need to include the header in source file
My inquiry is this. When does one use #import and when does one use #class?
Simple answer: You #import or #include when there is a physical dependency. Otherwise, you use forward declarations (#class MONClass, struct MONStruct, #protocol MONProtocol).
Here are some common examples of physical dependence:
Any C or C++ value (a pointer or reference is not a physical dependency). If you have a CGPoint as an ivar or property, the compiler will need to see the declaration of CGPoint.
Your superclass.
A method you use.
Sometimes if I use a #class declaration, I see a common compiler warning such as the following:
"warning: receiver 'FooController' is a forward class and corresponding #interface may not exist."
The compiler's actually very lenient in this regard. It will drop hints (such as the one above), but you can trash your stack easily if you ignore them and don't #import properly. Although it should (IMO), the compiler does not enforce this. In ARC, the compiler is more strict because it is responsible for reference counting. What happens is the compiler falls back on a default when it encounters an unknown method which you call. Every return value and parameter is assumed to be id. Thus, you ought to eradicate every warning from your codebases because this should be considered physical dependence. This is analogous to calling a C function which is not declared. With C, parameters are assumed to be int.
The reason you would favor forward declarations is that you can reduce your build times by factors because there is minimal dependence. With forward declarations, the compiler sees there is a name, and can correctly parse and compile the program without seeing the class declaration or all of its dependencies when there is no physical dependency. Clean builds take less time. Incremental builds take less time. Sure, you will end up spending a little more time making sure the all the headers you need are visible to every translation as a consequence, but this pays off in reduced build times quickly (assuming your project is not tiny).
If you use #import or #include instead, you're throwing a lot more work at the compiler than is necessary. You're also introducing complex header dependencies. You can liken this to a brute-force algorithm. When you #import, you're dragging in tons of unnecessary information, which requires a lot of memory, disk I/O, and CPU to parse and compile the sources.
ObjC is pretty close to ideal for a C based language with regards to dependency because NSObject types are never values -- NSObject types are always reference counted pointers. So you can get away with incredibly fast compile times if you structure your program's dependencies appropriately and forward where possible because there is very little physical dependence required. You can also declare properties in the class extensions to further minimize dependence. That's a huge bonus for large systems -- you would know the difference it makes if you have ever developed a large C++ codebase.
Therefore, my recommendation is to use forwards where possible, and then to #import where there is physical dependence. If you see the warning or another which implies physical dependence -- fix them all. The fix is to #import in your implementation file.
As you build libraries, you will likely classify some interfaces as a group, in which case you would #import that library where physical dependence is introduced (e.g. #import <AppKit/AppKit.h>). This can introduce dependence, but the library maintainers can often handle the physical dependencies for you as needed -- if they introduce a feature, they can minimize the impact it has on your builds.
I see a lot of "Do it this way" but I don't see any answers to "Why?"
So: Why should you #class in your header and #import only in your implementation? You're doubling your work by having to #class and #import all the time. Unless you make use of inheritance. In which case you'll be #importing multiple times for a single #class. Then you have to remember to remove from multiple different files if you suddenly decide you don't need access to a declaration anymore.
Importing the same file multiple times isn't an issue because of the nature of #import.
Compiling performance isn't really an issue either. If it were, we wouldn't be #importing Cocoa/Cocoa.h or the like in pretty much every header file we have.
if we do this
#interface Class_B : Class_A
mean we are inheriting the Class_A into Class_B, in Class_B we can access all the variables of class_A.
if we are doing this
#import ....
#class Class_A
#interface Class_B
here we saying that we are using the Class_A in our program, but if we want to use the Class_A variables in Class_B we have to #import Class_A in .m file(make a object and use it's function and variables).
for extra info about file dependencies & #import & #class check this out:
http://qualitycoding.org/file-dependencies/
itis good article
summary of the article
imports in header files:
#import the superclass you’re inheriting, and the protocols you’re implementing.
Forward-declare everything else (unless it comes from a framework
with a master header).
Try to eliminate all other #imports.
Declare protocols in their own headers to reduce dependencies.
Too many forward declarations? You have a Large Class.
imports in implementation files:
Eliminate cruft #imports that aren’t used.
If a method delegates to another object and returns what it gets
back, try to forward-declare that object instead of #importing it.
If including a module forces you to include level after level of
successive dependencies, you may have a set of classes that wants to
become a library. Build it as a separate library with a master
header, so everything can be brought in as a single prebuilt chunk.
Too many #imports? You have a Large Class.
When I develop, I have only three things in mind that never cause me any problems.
Import super classes
Import parent classes (when you have children and parents)
Import classes outside your project (like in frameworks and libraries)
For all other classes (subclasses and child classes in my project self), I declare them via forward-class.
If you try to declare a variable, or a property in your header file, which you didn't import yet, your gonna get an error saying that the compiler doesn't know this class.
Your first thought is probably #import it.
This may cause problems in some cases.
For example if you implement a bunch of C-methods in the header file, or structs, or something similar, because they shouldn't be imported multiple times.
Therefore you can tell the compiler with #class:
I know you don't know that class, but it exists. It's going to be imported or implemented elsewhere
It basically tells the compiler to shut up and compile, even though it's not sure if this class is ever going to be implemented.
You will usually use #import in the .m and #class in the .h files.
Forward declaration just to the prevent compiler from showing error.
the compiler will know that there is class with the name you've used in your header file to declare.
Compiler will complain only if you are going to use that class in such a way that the compiler needs to know its implementation.
Ex:
This could be like if you are going to derive your class from it or
If you are going to have an object of that class as a member variable (though rare).
It will not complain if you are just going to use it as a pointer. Of course, you will have to #import it in the implementation file (if you are instantiating an object of that class) since it needs to know the class contents to instantiate an object.
NOTE: #import is not same as #include. This means there is nothing called circular import. import is kind of a request for the compiler to look into a particular file for some information. If that information is already available, compiler ignores it.
Just try this, import A.h in B.h and B.h in A.h. There will be no problems or complaints and it will work fine too.
When to use #class
You use #class only if you don't even want to import a header in your header. This could be a case where you don't even care to know what that class will be. Cases where you may not even have a header for that class yet.
An example of this could be that you are writing two libraries. One class, lets call it A, exists in one library. This library includes a header from the second library. That header might have a pointer of A but again might not need to use it. If library 1 is not yet available, library B will not be blocked if you use #class. But if you are looking to import A.h, then library 2's progress is blocked.
Think of #class as telling the compiler "trust me, this exists".
Think of #import as copy-paste.
You want to minimize the number of imports you have for a number of reasons. Without any research, the first thing that comes to mind is it reduces compile time.
Notice that when you inherit from a class, you can't simply use a forward declaration. You need to import the file, so that the class you're declaring knows how it's defined.
This is an example scenario, where we need #class.
Consider if you wish to create a protocol within header file, which has a parameter with data type of the same class, then you can use #class. Please do remember that you can also declare protocols separately, this is just an example.
// DroneSearchField.h
#import <UIKit/UIKit.h>
#class DroneSearchField;
#protocol DroneSearchFieldDelegate<UITextFieldDelegate>
#optional
- (void)DroneTextFieldButtonClicked:(DroneSearchField *)textField;
#end
#interface DroneSearchField : UITextField
#end