So we have a library with header files as below (for instance):
Public
MyCustomClass.h (subclasses MyClass)
Private
MyClass.h
When this is imported into an app however it then complains that it can't find MyClass.h. This is fair enough. Its #imported into MyCustomClass.h and yet its hidden.
So I changed it to a forward class declaration #class MyClass. Now it complains that I can't use a forward declaration for a super class (also makes sense).
How can I get around this then? I need to subclass something, but I only want people using the library to have access to the child class, not the super class.
You're writing a library, and you want clients to instantiate MyCustomClass which inherits from MyClass. But clients should not ever instantiate MyClass.
Approach 1: You don't actually need or want to hide MyClass. You just want to avoid instantiating instances of it.
a) Make its constructor private
b) Create a factory method that creates instances of MyCustomClass.
The factory might be part of MyClass, or it could be elsewhere.
#implemenation MyClass
+ (MyCustomClass*) createWith: (Param*) someData;
Approach 2: consider composition rather than inheritance. Let MyCustomClass own an object of type MyClass, and let it do all the work:
#implementation MyCustomClass
#property (nonatomic,strong) MyClass* myClassInstance;
- (void) doSomething
{
[self.myClassInstance doSomething];
}
Since clients can't subclass MyClass anyway, the inheritance is an implementation detail. Don't inherit when you don't need to.
Approach 3: Are you sure you really want to expose MyCustomClass? Is it really an object, or is it a protocol? Perhaps your library should offer the interface publicly, and both MyClass and MyCustomClass are private implementations.
Related
I am working with a objective-C framework.
I have a public framework header "MyPublicHeader.h" exposed to the client application. I have a custom class in the project,
//MyCustomClass.h file
#interface MyCustomClass.h
- (NSString *) methodA;
#end
//MyCustomClass.m file
#inplementation
- (NSString *) methodA {
}
#end
If I want the client to instantiate the class I have to make it as public framework header. I want to hide the interface as a curiosity, is there any way to do it???
First know that nothing can be truely hidden in Objective-C due to the nature of dynamic dispatch and the features in the runtime which allow discovery of methods etc.
That said there are a number of ways to do this, a couple:
Use a subclass. Declare a superclass and publish its interface as part of your framework. Make your class a subclass of this and publish its interface only within the framework. You define one or more init methods in the superclass which return and instance of the subclass, and if you want to expose any further API define it in the superclass with dummy (or faulting) implementations and less the subclass override etc. This approach is similar to the model used for classes like NSString.
A .h file is just text and you can exploit this: make two .h files, say MyCustomClass.h and InternalMyCustomClass.h. In the first just declare the interface with no members, or the API you wish to make public, and publish that to users of the framework. In the second declare the real interface used within the framework. You must make sure to keep all three of the files (2 .h, .m) in sync. This approach would be call little naughty by some, "here be dragons" by others, or "needs must" by yet others...
You might also like to look into "class extensions" which are related to categories.
Hope that satiates your curiosity a little, and keep up with the curiosity its good (except for cats)!
You could create an empty wrapper class which only holds a reference to your MyCustomClass object.
When they create this object you secretly instantiate an object of your MyCustomClass inside and extract it when they pass you an object of the wrapper class.
Not sure if this is exactly what you want to achieve, but could be a workaround.
I am fairly new to realm of iOS. Coming from Java and Android background i am facing few challenges while learning objective C.
My question: I understand how the above three are different from each other but I fail to understand their use cases in practice.
Do we need a Class Extension for every class with private functions? What is the use of Category, when we can extend a Cocoa/Cocoa-touch class in interface and add custom functions? Please do provide some example from your experience.
Categories are a way to split a single class definition into multiple files.A category can be declared for any class, even if you don't have the original implementation source code.At runtime, there's no difference between a method added by a category and one that is implemented by the original class.
example for categories:
NSString+UrlString.h
#import <UIKit/UIKit.h>
#interface NSString(Additions)
+(void)urlMethod;
#end
NSString+UrlString.m//implmentation
#import "NSString+Additions.h"
#implementation NSString (Additions)
+(void)urlMethod
{
}
#end
The primary interface for a class is used to define the way that other classes are expected to interact with it. In other words, it’s the public interface to the class.
Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class itself.
Class extensions are used to declare private methods in objective C
For example, to define a property as readonly in the interface, but as readwrite in a class extension declared above the implementation, in order that the internal methods of the class can change the property value directly.
The methods declared by a class extension are implemented in the implementation block for the original class, so you can't, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString..
The syntax to declare a extension uses the #interface keyword, just like a standard Objective-C
#interface ClassName ()
#end
you may find that you wish to extend an existing class by adding behavior that is useful only in certain situations. Please refer this
Category is adding methods to a class in the runtime. As far as the runtime is concerned, the methods that are implemented in a class extension, ARE the methods that are available for the class itself. Category in Objective-C is a fancy name for Monkey Patching in other programming languages like C#. You can read about it here.
With that said, you can create a category for UIColor with some method if you want every UIColor to have that behaviour throughout that module. This isn't the case with subclassing. Only the subclassed (theoretically speaking) UIColor object will get those behaviour since there is a distinct difference in the type of the object.
Example:
UIColor has built in methods that give you different colors; you can call UIColor.greenColor() to get the green color; UIColor.blackColor() to get black color and so on...
Suppose you want your own to be called in a similar fashion, you create a category (example in swift) like so
extension UIColor {
static func yourColor() -> UIColor {
return UIColor(red:220/225,green:222/225,blue:223/225)
}
}
This way, it is valid for you to call UIColor.yourColor(). Every UIColor that you would use has this method available. Convenient than subclassing, isn't it?
Creating a subclass has polymorphic implications; categories don't. You subclass only when you need refinement of an existing class and treat it both as a parent and the child when required. As a Java developer you would know when it makes sense to subclass.
An extension is best for private methods which you would like to declare in your .m file. Think of extension as a category private to the .m file.
Class Extesions: If you mean by Extension Methods like in .Net, then it called as Category in Objective-C.
Categories: These are nothing but the Extension Methods, it allows to add methods in existing classes from iOS SDK (like NSString, NSURL, etc.)
For more details: Apple Doc: Category
Primary Interface: Writing a class (Interface in terms of Objective-C) definition inside its implementation file called primary interface.
//ClassName.mm #interface ClassName() {
Declarations;
}
- Methods;
+ Methods;
#end
#implementation ClassName
#end
So, Categories are also one type of primary interfaces.
Imagine I have define a class MyClass as follows:
The class interface file:
#import <Foundation/Foundation.h>
#interface MyClass : NSObject
#property (nonatomic) NSString *myProperty;
- (void)myPublicMethod;
#end
The class implementation file using categories:
#import "MyClass.h"
#interface MyClass (MyCategory)
- (void)myPrivateMethod;
#end
#implementation MyClass
- (void)myPublicMethod {
NSLog(#"myPublicMethod was called!");
[self myPrivateMethod];
}
- (void)myPrivateMethod {
NSLog(#"myPrivateMethod was called!");
}
#end
An alternative class implementation file NOT using categories:
#import "MyClass.h"
# implementation MyClass
- (void)myPublicMethod {
NSLog(#"myPublicMethod was called!");
[self myPrivateMethod];
}
- (void)myPrivateMethod {
NSLog(#"myPrivateMethod was called!");
}
#end
Was hoping someone could explain the difference between the two implementation file approaches.
Is it the case that using categories means the "private" methods are inherited by any subclasses of MyClass and not using categories means the "private" methods are not inherited by any subclasses?
All methods that exist on a class are always inherited and are callable by anyone regardless of how you declare them. The main difference is whether anybody knows about them. There was also a historic need to declare things before use which leads to internal forward declarations in older and old-style code.
A category is used to add methods to an existing class. A common use is to extend the functionality of one of the existing classes. For example you might implement:
#interface NSURL (HTTPQueryParameters)
- (NSDictionary *)httpQueryParameters;
#end
So from then on you've given NSURL itself the knowledge required to parse HTTP protocol query parameters. It's often the correct factoring to add functionality directly to classes you don't have the source for.
Objective-C used to follow the C rule that methods had knowledge only of those methods that had preceded them within the compilation unit. So to be able to call a method that appeared later in the source file you'd need a forward declaration. If you didn't want to publish that method for the world to see you could achieve that with a category or a class extension (which for this purpose is just an unnamed category).
Nowadays Objective-C methods can call any method that is defined anywhere within the compilation unit, including subsequently in the same source file. It's therefore now normal not to collect up your unpublished methods into a category or an extension just for the benefit of the compiler.
That leaves categories for:
adding functionality to existing classes; and
segmenting your classes if they become very large;
Class extensions are now primarily for:
declaring #propertys without publishing them.
In Objective-C any method call can be sent to any object — objects are dynamically typed. So there's a mapping table in memory at runtime for every class from method name to implementation. The lookup process is to see whether the method is implemented in the class dispatched to. If not then dispatch to the superclass. An exception will be raised if the runtime runs out of superclasses.
The declaration of the method in a category #interface only serves to expose the method to users of the class, including -- as you mentioned in your comment -- subclasses.
(It would be much more usual to use a class extension (sometimes called an "anonymous category") declare a method that you're defining in the main implementation block. Actually, I'm not 100% sure what the interaction is between your category declaration and the main block definition -- I wouldn't have been surprised if it didn't compile, but it does.)
Thus, the only difference between your two examples is that the declaration allows you to create a private header in a situation where you want your own subclasses to access this method, but have framework users who you want to restrict.
I am subclassing a pod's class, and in this class there's a private instance variable that I want to expose and use within my class:
#interface MySuperClass () {
UIScrollView *_scrollView;
}
Usually with exposing a private member or method, I would use a category like someone previously mentioned here, but I am having a problem doing it with a private instance variable. I read here that Associative References might work, but I wasn't able to make it work.
Try implementing in child class:
- (UIScrollView *)scrollView {
return [self valueForKey:#"_scrollView"]
}
Unfortunately, in Objective-C there is no way to declare private instance variables.
Whatever you want your subclass to be able to see, you'll have to declare in your .h-file. The Associative References that you were talking about work in that exact same way, but they solve a different problem, namely the one of declaring instance variables in a category.
This is due to the design of the language, and I guess it makes sense in the way that .m files are really implementation files, and no other class should actually care about the implementation of another, even with inheritance relationships like subclassing.
The option for you with the private instance variable of that pod's class would be to either put it in a property or indeed implement a category where you add methods to access it.
I am actually a newby at xcode. I can make out a few things be myself but have questions about what some things do and why they are put there. I have tried to read many e-books, watched tutorials, but they never go into the basics, alway just say "Add this, Click here etc"
Could someone give me some answers to a few questions please.
Ok, I know an ios app is mostly made out of Views, views are controlled by controllers. Each controller has a header (.h) file and a module?class? file (.m). The .h file contains the declarations of variables and functions used in the .m file.
The whole app is controlled by a master "controller" called the "delegate".
Definitions in .h file may be for example an action IBAction or IBLabel or something.
What raises questions for me is for example these lines:
#class FlipsideViewController;
#protocol FlipsideViewControllerDelegate
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
#end
#interface FlipsideViewController : UIViewController
#property (nonatomic, assign) id <FlipsideViewControllerDelegate> delegate;
- (IBAction)done:(id)sender;
and why are sometimes in another view controller the delegate class loaded
#class MainViewController;
what does the following do, meaning what is the #interface declaration?
#interface flipAppDelegate : NSObject <UIApplicationDelegate>
what is
nonatomic, retain
sorry for asking really stupid questions, but every tutorial just skips these things.
I can follow a youtube video or a manual, but it doesn't teach me a lot...
Let me try to answer your questions, one at a time.
what is the #interface declaration?
The interface declares a class. By declaring a class, I mean it specifies the instance variables and private/public methods that it contains. Again, the header file only contains the declaration of the methods, and the implementation/body of the methods lies in the module class. So, here-
#interface FlipsideViewController : UIViewController
The class FlipsideViewController derives from/subclasses/extends UIViewController. i.e Is a type of UIViewController but adds its own features.
Similarly
#interface flipAppDelegate : NSObject <UIApplicationDelegate>
Subclasses NSObject and implements the UIApplicationDelegate protocol. A protocol is essentially a set of methods that a class promises to implement (although there can be optional methods).
why are sometimes in another view controller the delegate class loaded
The delegate pattern allows a class to delegate its work to another class that implements the delegate protocol. So, here, FlipsideViewController keeps an instance of the delegate object, so that its flipsideViewControllerDidFinish: can be called.
what is nonatomic, retain
It means that when you set a value to your instance variable, the value's refcount will be incremented and set to your variable. Also, it will not happen as an atomic operation. You need atomic only in a multi-threaded environment.
#synthesize is simply a shortcut to generate getters and setters for your variables.
You really need to read the Objective-C Programming Language from Apple. It's pretty brief, and runs down the basics of the architecture, concepts, and syntax.
To address, briefly, some specifics:
The #class directive is used to declare the name of a class without importing it's header file. It is often used in a .h file declaring a protocol, because a protocol has no implementation, it doesn't need to import the interfaces of other classes (their .h files).
A protocol is a way of declaring what methods and properties a class should have in order to "implement" the protocol.
#interface is used in an interface file (.h) to declare a class, meaning to describe the methods and properties it will have, the protocols it will implement, and the superclasses from which it will inherit. In your example, the class will be called flipAppDelegate, which inherits all of the methods and properties of the NSObject class, and which implements the UIApplicationDelegate protocol.
In your class (.m) file, you will define (with all your code) all of the methods and properties that you declared in your interface file. You include the methods and properties you declared yourself, and from the protocols you implement.
#synthesize is used in a class implementation file (.m) to "synthesize" --- that is, automatically create the code for --- all the properties you declared in your interface (.h) file. Since properties normally just need basic accessors (a "getter" that just returns the current value, and a "setter" that just sets the current value), using #synthesize is a shortcut to let the compiler create the variable to store the value, the getter method, and the setter method for you automatically.
Xcode = An IDE (Integrated Development Environment)
Objective-C = A Language
Cocoa Touch, Media FrameWork, Core FrameWork = Frameworks used in developing for iOS
I'd highly recommend starting by learning Objective-C. At least with a primer first:
https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html
There's a wealth of tutorials and videos available from Apple for developers you might want to start on the developer portal.