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.
Related
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.
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.
Inheriting code from other developers has made me a firm believer in keeping as many messages as possible out of a class' public interface by means of a Class Extension. I'm also a firm believer in adopting special naming conventions for private, implementation-specific members of a class. I really like being able to tell at a glance what messages being sent and what members being referenced within the implementation context are not ever intended for public use and vice versa. If nothing else, it makes the overall semantics of a class easier for me grasp more quickly, and that's worth it.
Justification aside, I've written boatloads of classes with boatloads2 of private methods, but I've never really come up with a pattern for naming that I really love (like I do the controversial ivar_ convention for ivars). Notable examples:
#interface myClass()
// I like this, but as we all know, Apple has dibs on this one,
// and method name collisions are nasty.
- (void)_myPrivateMessage;
// The suffix version promoted by Google for ivars doesn't really translate
// well to method names in Objective-C, because of the way the method
// signature can be broken into several parts.
- (void)doWork_; // That's okay...
- (void)doWork_:(id)work with_:(id)something; // That's just ugly and tedious...
- (void)doWork_:(id)work with_:(id)something and_:(id)another; // My eyes...
// This version is suggested by Apple, and has the benefit of being officially
// recommended. Alas, I don't like it: The capital letter is ugly. I don't like
// underscores in the middle of the name. Worst of all, I have to type three characters
// before code-sense does anything more useful than inform me that I am typing.
- (void)BF_doWork;
#end
At this point, there are a kajillion different means by which I could mangle my private method names, but instead of making something up, I figured I would first take a poll for any popular conventions I may not be aware of. So, what have you used?
I don't distinguish private methods by name. Instead, I keep them out of the public interface by declaring them in the class extension portion of the .m file, thus:
#interface MyClass ()
- (void)doWork;
#end
I use double underscore for my private methods:
- (void)__doSomethingPrivate;
It almost looks like the single underscore-syntax (good readable) and at the same time confirms to the Apple guides.
I use a prefix, no underscore. The prefix is generally related to the name of the project in question. If you do use underscores, there's no need to have more than one.
I use two levels of private methods: slightly private and very private. Slightly private methods are methods which could become public, but currently aren't. They are usually convenience methods that I use internally, and I usually don't put in as much protection unless I decide to make it public. For very private methods, I ignore apple and use an underscore prefix. Since 99% of my code is in classes I create and I usually have prefixes on my class names, the chances of running into naming problems is small. When adding code to classes I didn't make, I rarely make private methods, but add a short prefix on the rare occasion that I do.
I prefix private methods with a 'p':
(void) pDoWork;
(void) pDoWork:(id)work with:(id)something;
Similarly, I use 's' for static (or class) methods:
(Universe*)sGet; // used to return singleton Universe object.
Beyond naming conventions, I declare private methods in .m files instead of .h files.
Using a fixed prefix will help to "hide" the method from the outside world but it won't prevent a method from being accidentally overridden. E.g. I once extended a class and I made a method:
- (void)private_close
{
// ...
}
The result was that the behavior of the class broke in horrible ways. But why? It turned out, the super class also had a method name private_close and I was accidentally overriding it without calling super! How should I know? No compiler warning!
No matter if your prefix is _ or __ or p or private_, if it is always the same, you will end up with problems like this one.
So I prefix private methods (and properties!) with a prefix that resembles the class name. Therefor I take the upper case letters of the class name to form the "private prefix":
ComplexFileParser -> CFP
URLDownloadTask -> URLDT
SessionController -> SC
This is still not perfectly safe, yet it is very unlikely that a subclass with a different name has the same still the same private prefix.
Also when you do frameworks, you should prefix all classes and other symbols with a framework prefix (as Apple does with NS..., CF..., CA..., SC..., UI..., etc.) and thus this class prefix is part of the private prefix as well making collisions even less likely:
Framework DecodingUtils.framework -> DU
Class ComplexFileDecoder in framework -> DUComplexFileDecoder
Private Prefix -> DUCFD
Private Method close -> - (void)DUCFD_close
Alternatively append the prefix at the end of the fist method argument name, to get better auto-completion:
- (void)doSomethingWith:(Type1)var1 parameters:(Type2)var2
will become
- (void)doSomethingWith_DUCFD:(Type1)var1 parameters:(Type2)var2
or always only append it to the last parameter name:
- (void)doSomethingWith:(Type1)var1 parameters_DUCFD:(Type2)var2
or (now it gets really crazy) - add a fake dummy parameter just for naming:
- (void)doSomethingWith:(Type1)var1 parameters:(Type2)var2 DUCFD:(id)x
where x is actually never used in the method and you pass nil for it:
[self doSomethingWith:var1 parameters:var2 DUCFD:nil];
and as it will always be the same at the end, use a pre-processor macro:
#define priv DUCFD:nil
#define PRIVATE DUCFD:nil
// ...
[self doSomethingWith:var1 parameters:var2 priv];
[self doSomethingWith:var1 parameters:var2 PRIVATE];
Prefix and suffixing works also with properties (and thus their ivar, getter/setter methods), the preproessor trick above won't, of course.
Regarding Apple recommendations. You might be interested in how Apple writes it's own code.
If you check private APIs you will see that they use underscores for private methods everywhere. Every peace of Obj-C code in iOS uses them. And in many cases those methods go through multiple iOS versions without refactoring or renaming which means it's not a temporary solution for them but rather a convention. In fact, there're three levels of private methods they use extensively - no underscore, single and double underscore.
As for other solutions like "private", class or project name prefixes - they don't use them at all. Just underscores.
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!
After several months of coding in Objective-C, I completely understand when I need an #import, how import statements cascade (ripple?), and when to use forwarding classes. I do not know how to aggregate imports to get them inside of <> instead of in quotes (although maybe that's just for frameworks)...
The problem is that I'm making a huge mess. I come from Java (and the heavy-handed IDE), so I just add imports as I see fit. Sometimes I add them to the interface, but since that's usually not necessary, I just add them to the top of the .m in question.
Today I started thinking: there must be some rules of thumb on how to organize this stuff. In fact, since Objective-C is a C superset, there are rules of thumb for everything, but I don't know them. How should I organize my imports? Particularly:
When should I import in the .m?
When should I import in the .h?
Should I create .h files just for the sake of importing them (i.e., header files that just have imports in them)? If so, any hints on organizing that?
This is just a general idea of what I'm trying to figure out.
The <....> syntax is indeed just for frameworks. That doesn't mean you shouldn't create a framework to contain the core logic of your application though. Often this is a useful thing to do if you:
a) Need to provide support for loadable bundles that want to invoke aspects of your application logic (the bundle links to the framework, so does your application)
b) Write multiple apps that share the same core logic
Your question is somewhat subjective and you will get developers who argues both ways, but a convention I follow is:
Never import class definitions in the .h file, unless you are subclassing it. Use forward #class directives for everything in the .h.
Only import class definitions into a .m as you find you need to use that class in the implementation.
Generally speaking, the .h does not need access to the class definition of its ivars, method arguments or return values. It only needs to know that they are classes, which is what #class allows you to do. It does need access to the class definition of anything you're subclassing, adding a category to, or (obviously) implementing a protocol for.
Forget about whether <...> is for frameworks or what. <...> checks the system header search path, while "..." checks the current dir in addition to. One thing to remember however, is that the <CoreFoo/CoreFoo.h> declaration is handled a little differently on the apple platform, but only as it relates to apple frameworks: CoreFoo.framework/Headers/CoreFoo.h is matched to CoreFoo/CoreFoo.h
When imports are inside <> instead of quotes, all this means is that you are importing something from a framework. In fact, when doing this, the import is typically in the style
#import <Foundation/Foundation.h>
The first Foundation, before the slash, is the name of the framework in question, and the second one is just a header file in that framework. That header file is just something like
#import <Foundation/NSObjCRuntime.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSAutoreleasePool.h>
...
#import <Foundation/NSURLHandle.h>
including every file from that framework. You can do this too, and isn't a bad idea for components that need multiple imports (although in that scenario, you may want a separate public interface)
For the other stuff, following the rule of thumb that you want stuff to know about as little as possible, you only want to put the import in the header file if it's necessary (like for an ivar or superclass) but really it's a matter of taste.