I studied about extensions and now i have some queries on some points of extension use.
Point : Extensions extend the functionality of classes for which we have source code.
Query : If we already have source code for a class then we can easily write all the required methods in header file and in implementation file.So why we are using extension for this feature.
Point : Extensions also provide the alternative to private methods.
Query : we can write private methods in private interface in .m file.so why we are using extension for this feature also.
Point : Extensions makes a property readonly for other classes and readwrite for original class.
Query : this functionality also can be achieved by redefining the readonly property in implementation file with readwrite properties.
Confused with these queries, the actual concept behind the extensions.Any help would be appreciated.
The previous two answers have confused categories with class extensions, which is an easy mistake to make since Swift calls "extensions" what Objective-C calls "categories". But class extensions in Objective-C are a separate thing. As opposed to a category, which is declared like this:
#interface SomeoneElsesClass (MyCategoryName)
an Objective-C class extension is declared with nothing in the parens, like this:
#interface MyClass ()
The major differences between the two are that 1) unlike categories, an extension can only be declared for a class for which you have the source code, 2) unlike categories, which need a separate #implementation block, the implementation for anything you declare in the extension goes in the main #implementation block for the class, and 3) extensions can add stored properties, whereas categories cannot.
The primary thing extensions are used for is adding private stored properties, and extending publicly read-only properties to be writable. This can be done by other means, yes, but it requires more code. For example, a private property can be added via an extension like so:
#interface MyClass ()
#property (nonatomic, copy) NSString *someProperty;
#end
whereas to do it in the implementation, you'd have to make an ivar and then write the accessors:
#implementation MyClass {
NSString *_someIvar;
}
- (NSString *)someProperty {
return self->_someIvar;
}
- (void)setSomeProperty:(NSString *)str {
self->_someIvar = [str copy];
}
#end
As you see, the extension results in fewer lines of code, and clearer code overall. Similarly, adding read-write support to a publicly read-only property is more succinct and communicates what you want to do more clearly than writing out a setter.
Extensions can also be useful when writing library and/or framework code, because you can put an extension in an internal header file which is #imported by other source files in the framework project but not published as a public header. In this way, you can expose methods to other framework code but not to clients of the framework. In this way, you can get the same functionality that is provided by Swift's internal keyword. This can, of course, also be done with categories, but extensions provide a cleaner way to do it, since the corresponding implementation of the methods will not have to be in a separate #implementation block.
See the documentation for more information: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html#//apple_ref/doc/uid/TP40011210-CH6-SW3
My Objective-C is getting rusty, and there are subtle differences in the use of extensions in Swift, but I'll take a stab at answering your questions:
Extensions let you extend the functionality for classes for which you don't have the source code. This includes system classes.
Extensions also let you group methods into logical groupings for clarity. For example, you might create an extension that defines all the methods needed to conform to a protocol.
Yes, you can use an extension to make a property read/write inside a class and readonly for external users of the class, and you can also do that by redefining the property in the implementation. This is a matter of style. It's common to have more than one way to achieve something in programming.
If we already have source code for a class then we can easily write all the required methods in header file and in implementation file.So why we are using extension for this feature.
That is rather targeted at the classes you didn't write yourself and don't have access nor the ability to modify their source code - like UIKit or Foundation classes. Sure, you can subclass them, but if you have a fairly large codebase and want to add additional functionality to a class, then without extensions (or rather, categories in Objective-C) you'd need to rewrite your codebase to use the derived class.
we can write private methods in private interface in .m file.so why we are using extension for this feature also.
and
this functionality also can be achieved by redefining the readonly property in implementation file with readwrite properties.
That only works within the single .m file defining the class - what if you want to have readwrite access to classes properties or access to private methods within entire module (for example, a framework you're writing), but readonly outside of it, as well as not exposing the methods? Categories provide you the means for that.
Related
I have a method declared in Objective-C protocol:
#protocol QMChatConnectionDelegate <NSObject>
#optional
- (void)chatServiceChatDidConnect:(QMChatService *)chatService;
I want to use this method as callback in my .swift file. My question what is difference between using chatServiceChatDidConnect method directly in class body or adding it as part of extension:
class Chat: NSObject, QMChatConnectionDelegate
{
...
func chatServiceChatDidConnect(chatService: QMChatService!) {
print("connected")
}
}
or
class Chat: NSObject, QMChatConnectionDelegate
{
...
}
extension Chat: QMChatConnectionDelegate {
func chatServiceChatDidConnect(chatService: QMChatService!) {
print("connected")
}
}
and do I need to declare it as extension Chat : QMChatConnectionDelegate {} or just extension Chat {}
There are two questions being asked here, so I'll try to address both of them as directly as possible.
What is difference between using chatServiceChatDidConnect method directly in class body or adding it as part of extension?
Depending on what you mean by "difference", the answer is either "nothing" or "very little".
Once your project is compiled, there will be no difference. During compilation, it might take slightly longer, but I doubt the difference is noticeable enough to care. During development, the difference is mostly organizational, but perhaps partly architectural.
If you do not move the extension to a separate file, the difference is going to be purely organizational. If you have a class conforming to multiple protocols or particularly large protocols, organizing the protocol conformance into extensions can be beneficial when it comes to human-parsing of the class.
If you do move the extension into a separate file, you can obtain some architectural differences as well when we consider how the private access modifier works in Swift (or also the default internal when we consider that the extension could be not just a different file, but a different module, but for simplicity sake, let's focus on private).
Consider conforming to a UITableViewDataSource protocol. Conceivably, we might want some helper methods when it comes to returning a cell from tableView(_:cellForRowAtIndexPath:), and if that's the case, tableView(_:cellForRowAtIndexPath:) is probably the only method that actually needs to call those methods. If that's the case, we can create the protocol conformance in an extension in a separate file and mark all of the helper methods as private. Now we've narrowed the scope of those helper methods to just that extension (which should be the only place that needs it).
Do I need to declare it as extension Chat: QMChatConnectionDelegate {} or just extension Chat {}?
The answer to this is it depends.
Certainly, you don't need to mark your class as conforming to a protocol in multiple places. Just one will do. And while extensions can have different access level than the class they extend (a private extension of an internal class for example), they can not have an access level broader than the class they extend (a public extension of an internal class is not allowed, for example).
What makes most sense to me is to not mark the class as conforming to the protocol but mark the extension as conforming to the protocol:
class Chat: NSObject {}
extension Chat: QMChatConnectionDelegate {}
Importantly, when we create our classes & extensions like this, it keeps our code quite modular. Our class shouldn't rely on anything in the extension. It should function entirely without it, and removing the extension allow our class to still work properly (just not for using the QMChatConnection).
First of all extension declaration is valid only from the file scope, so your second example should look like that:
class Chat: NSObject
{
...
}
extension Chat : QMChatConnectionDelegate {
func chatServiceChatDidConnect(chatService: QMChatService!) {
print("connected")
}
Secondly you shouldn't re-declare protocol conformance in both class declaration and extension.
You should treat Swift extension more or less like categories in Objective-C.
Answering your questions, there is no big difference if you declare method conforming to a protocol directly in the class scope or in the extension.
Adding protocol conformance in extensions can have several benefits:
You can add methods implementing certain protocol in a separate file
You can add protocol conformance to existing classes, without modifying their body. So in the end you can add protocol conformance to 3rd party classes
It allows for a nice logical organization of your source code.
I have a baseClass1.h an d baseClass1.m
These have several public methods which are used by several base classes. What I am trying to do is to create a different implementation of same methods declarations.
After I have written baseClass2.m whose interface is baseClass1.h also.
Now in subclasses, how do I have methods do what I've defined in baseClass2.m instead of their respective definition from baseClass1.m
EDIT:
I duplicated the target in baseClass1 workspace to a new target. Both implementation files are exclusive to 2 targets. What I'm trying to do is to use different .m file with each target selection from xCode.
It is somewhat like changing the AP definitions. To explore the possibility to discard baseClass1.m for given now. Any way so that even if I delete baseClass1.m and program should still build
If you want two different implementations of the same class in two different targets then you can simply use two separate implementation files for the same class, and add each of them to one target only, e.g.
"BaseClass.h": the interface,
"BaseClassA.m": implementation of BaseClass, only in target A,
"BaseClassB.m": implementation of BaseClass, only in target B.
An implementation file need not have the same name as class, that is just a (useful) convention.
You need create #protocol for common interface.
Implement it's methods in baseClass1 and baseClass2.
And then you can subclass any base class you wish.
You can use protocol to declare common interface.
baseProtocol.h:
#protocol your_protocol <NSObject>
#optional
- (void)methodA;
#required
- (void)methodB;
#end
baseClass1.h:
#import "baseProtocol.h"
#interface baseClass1 : NSObject<your_protocol>
#end
baseClass2.h:
#import "baseProtocol.h"
#interface baseClass2 : NSObject<your_protocol>
#end
Technically this is possible: easy, in fact.
It is also a Bad Idea™.
Why is it a bad idea? Because it is unexpected. It is very unexpected. So unexpected, that some people didn't think it possible, many more didn't even understand what you where asking.
By using this anti-pattern, you are dooming future developer to waste hours trying to figure out what you did, and why you did it.
In this example, just use a protocol, fake it out by using a cluster class, or just support both implementations in a single class using a flag to switch between the two. Don't make things harder on everyone just because you can be clever with the build system.
I was under the impression that class extensions in Objective C were just anonymous categories. However, you may add properties to these class extensions, which is impossible in categories, so I'm a bit confused:
#import "Money.h"
#interface Money ()
#property(nonatomic) NSUInteger amount;
#end
#implementation Money
#end
How are class extensions implemented? As categories? Then why are you allowed to add iVars to it? When are class extensions added to the class, in compile time or when the class is loaded?
Class extensions are a compiler mechanism that allows offsetting a subset of the instance variables, declared properties and methods declared in #interface to a specific translation unit (e.g., from a public header file to an implementation file), thus allowing header files to declare only what is supposed to be public. From the runtime perspective, extensions do not exist: everything that is declared in a class extension is merged onto the principal class. This implies that extensions must be compiled along its principal class (as opposed to categories), which you can infer from the fact that you have a single #implementation for both the principal class and its extension. It’s all part of the same class.
As you can see, class extensions are quite different from categories. Categories cannot declare instance variables, categories can reside in implementation files different from the one that implements the principal class (including classes declared and implemented in libraries) and they have their own #implementation. Furthermore, categories are explicitly loaded and attached to the principal class by the runtime.
I left the original, so people can understand the context for the comments. Hopefully, this example will better help explain what I am after.
Can I create a class in Obj-C that has file-scope visibility?
For example, I have written a method-sqizzling category on NSNotificationCenter which will automatically remove any observer when it deallocs.
I use a helper class in the implementation, and to prevent name collision, I have devised a naming scheme. The category is NSNotificationCenter (WJHAutoRemoval), so the private helper class that is used in this code is named...
WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
That's a mouthful, and currently I just do this...
#define BlockObserver WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
and just use BlockObserver in the code.
However, I don't like that solution.
I want to tell the compiler, "Hey, this class is named Bar. My code will access it as Bar, but I'm really the only one that needs to know. Generate a funky name yourself, or better yet, don't even export the symbol since I'm the only one who should care."
For plain C, I would is "static" and for C++ "namespace { }"
What is the preferred/best/only way to do this in Obj-C?
Original Question
I want to use a helper class inside the implementation of another. However, I do not want external linkage. Right now, I'm just making the helper class name painfully unique so I will not get duplicate linker symbols.
I can use static C functions, but I want to write a helper class, with linker visibility only inside the compilation unit.
For example, I'd like to have something like the following in multiple .m files, with each "Helper" unique to that file, and no other compilation unit having linker access. If I had this in 10 different files, I'd have 10 separate classes.
#interface Helper : NSObject
...
#end
#implementation Helper : NSObject
...
#end
I have been unable to find even a hint of this anywhere, and my feeble attempts at prepending "static" to the interface/implementation were wrought with errors.
Thanks!
I don't believe you will be able to do what you want because of the Objective-C Runtime. All of your classes are loaded into the runtime and multiple classes with the same name will conflict with each other.
Objective-C is a dynamic language. Unlike other languages which bind method calls at compile time, Objective-C does method resolution at invocation (every invocation). The runtime finds the class in the runtime and then finds the method in the class. The runtime can't support distinct classes with the same name and Objective-C doesn't support namespaces to seperate your classes.
If your Helper classes are different in each case they will need distinct class names (multiple classes with the same name sounds like a bad idea to me, in any language). If they are the same then why do you want to declare them separately.
I think you need to rethink your strategy as what you are trying to do doesn't sound very Objective-C or Cocoa.
There's no way to make a class "hidden." As mttrb notes, classes are accessible by name through the runtime. This isn't like C and C++ where class are just symbols that are resolved to addresses by the linker. Every class is injected into the class hierarchy.
But I'm unclear why you need this anyway. If you have a private class WJHAutoRemovalHelper or whatever, it seems very unlikely to collide with anyone else any more than private Apple classes or private 3rdparty framework classes collide. There's no reason to go to heroic lengths to make it obscure; prefixing with WJHAutoRemoval should be plenty to make it unique. Is there some deeper problem you're trying to fix?
BTW as an aside: How are you implementing the rest of this? Are you ISA-swizzling the observer to override its dealloc? This seems a lot of tricky code to make a very small thing slightly more convenient.
Regarding the question of "private" classes, what you're suggesting is possible if you do it by hand, but there really is no reason for it. You can generate a random, unique classname, call objc_allocateClassPair() and objc_registerClassPair on it, and then assign that to a Class variable at runtime. (And then call class_addMethod and class_addIvar to build it up. You can then always refer to it by that variable when you need it. It's still accessible of course at runtime by calling objc_getClassList, but there won't be a symbol for the classname in the system.
But this is a lot of work and complexity for no benefit. ObjC does not spend much time worrying about protecting the program from itself the way C++ does. It uses naming conventions and compiler warning to tell you when you're doing things wrong, and expects that as a good programmer you're going to avoid doing things wrong.
Learning Objective-C and other c based Languages I learned that you should put the #includes and the #imports in the header file. And the #class goes there as well. Recently looking at example code from apple and other sources around the web the #class is in the header and all the imports are in the implementation file.
Which is correct? Are there reasons for both? Also why do you need to provide the #class declaration if you are importing the header file.
Neither case is "more correct", there are definitely reasons for both behaviours. For example, think about the case where you have two classes, each which has a reference to an object of the other type:
ClassA.h:
#interface ClassA : NSObject
{
ClassB *b;
}
ClassB.h:
#interface ClassB : NSObject
{
ClassA *a;
}
This code won't compile - you have a circular dependency in these headers. The solution is to forward declare the required classes using the #class directive.
A situation where you might prefer the #import directive in the header file might be if you have some common code besides just a class name that you care about in the other header - maybe C style functions or enumerated types or something.
Learning Objective-C and other c based Languages I learned that you should put the #includes and the #imports in the header file.
no - not in c based languages. you should put them in the implementation files where possible. you can't always create a zero-dependency header, but you should minimize it.
c based languages take a long time to compile, especially when the dependencies and includes are very complex, or there are unnecesary includes (introducing more dependency, coincidentally).
And the #class goes there as well. Recently looking at example code from apple and other sources around the web the #class is in the header and all the imports are in the implementation file. Which is correct?
use forward declarations (#class NAME;, #protocol NAME;, struct NAME, class NAME;`, etc.) wherever you can.
Are there reasons for both?
including in the header is the lazy way, it slows down your build times and introduces a lot of dependency. it's convenient because you don't have to write as many include/import declarations, but it's not considerate for people who must use your programs.
Also why do you need to provide the #class declaration if you are importing the header file.
if the class interface is already visible (has been included already, or another file has declared it), you do not need both . you'll need the interface visible if you intend to use the type (apart from some very trivial cases).
you certainly won't be excited to correct the mistake once your build times have grown slow -- it's best to learn and implement using the right approach. if you've not developed a complex c project, then you'd likely be very surprised to learn how much time is lost while compiling.
if you expect that your programs will never become nontrivial, and will be never shared or reused, then do whichever you prefer.
good luck!