Multiple inheritance design issue in iOS - ios

I have below classes
#interface Document : NSObject
//Root document
#end
#interface ExtendedDocument1 : Document
//sublcass of document, with specific behaviour
#end
#interface ExtendedDocument2 : Document
//sublcass of document, with specific behaviour
#end
#interface EncryptedDocument : Document
//Supports encryption of document
#end
If I want to encrypt the ExtendedDocument(1/2), how can I achived this? If I subclass the ExtendedDocument with EncryptedDocument, the extended document will become encrypted by default.
How to solve this design issue? which pattern I can use to solve this kind of problems. Looks like I am missing something.

You could receive an intermediary interface reference in the EncryptedDocument initializer. To do so, you must find out which is the minimally sufficient interface between all your class interfaces needed to expose information for documents to be encrypted. It may so happen that Document does the job. If not, you should create this interface and extend all others from it, or create a protocol, and make your classes implement it. Then, just add a specialized initializer for EncryptedDocument:
#interface EncryptedDocument
- (id)initWith:(Document*)document;
// whatever else an encrypted document has to expose in its interface ...
#end
This has the advantage of keeping the original plain document untouched, and if you don't need it anymore you can release it for garbage collection.
But in this case you might want to separate the responsibility of actually implementing the encryption, which is the job of an algorithm implementation, from the EncryptedDocument representation, which is more tied to the data model of such a document. One way to achieve that is to employ the Strategy Design pattern and remove the encryption work from the EncryptedDocument. Perhaps you could remove the EncryptedDocument altogether from the hierarchy, changing the return value for the encrypt method bellow. But this depends more on your data model and application domain. (https://en.wikipedia.org/wiki/Strategy_pattern).
#interface DocumentCypher
- (id)initWithMethod:(id<CypherMethod>)method;
- (EncryptedDocument*)encrypt:(Document*)plainText;
#end;
But this depends on the complexity of the problem you are trying to tackle, the more "naive" and simple solution could be easily refactored when the need for introducing more complex behavior arises.

What you are missing is that inheritance is not the swiss army knife of programming. In that specific case, a protocol such as Encryptable can help support an interface implementation and call an instance of an object by referring to the protocol type. Check the following link:
Working with Protocols

Related

Without exposing the interface in the public header of framework can I pass a custom object to the client application?

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.

Property or not property?

Quick question about semantics :)
If I was writing a protocol, which is preferred:
// (a)
#protocol MyProtocol
#property (nonatomic, copy) NSSet *things;
#end
vs.
// (b)
#protocol MyProtocol
- (NSSet *)things;
- (void)setThings:(NSSet *)things;
#end
(a) is cleaner code but has the implication that implementing classes will have an ivar for things, which isn't the case in my project. Because of my use case, things cannot be KVO either. It also implies that the implementing class will copy things, which it's not doing in every case for me.
(b) is more accurate code (it's very explicit about what you can / can't do i.e. no KVO) but it's a little messier.
Any opinions?
I am amending my answer that (a) probably is not best for a protocol but best for a non-protocol interface.
I would go with the #property. How a property is implemented is an implementation detail and I never consider that from the outside.
Consider a v1 implementation where the property is only that. In v2 the internals are changed and either the setter or getter is made a method. Totally reasonable, one of the reasons that properties are good, they allow such changes, they hide the implementation details.
Also consider the opposite, in the next version where is is desired to remove the methods and replace them with a property. Again an implementation detail that a property in the first instance covers quite well.
Finally, in this case there is a copy attribute which provided explicit information of how a call with a mutable object will be handled, that is lost in the method implementation.
Protocols define messaging contracts [1]. They are not intended to store data. According to the Apple documentation you are only supposed to add properties to class extensions (you can add properties to categories but the compiler won't synthesize an ivar) [2]. Depending on what you are trying to do I would use one of the two following approaches to be consistent with the documented usage of the Objective-C language:
If you have the source code of the class (its one you created) then use a class extension.
If you do not have the source code sub-class the object.
That being said, if you really need to do it the other way use option (b). It is more corect and more correct is cleaner code!
Here is another question that deals with the same issue.
Good luck
I think case 'a' makes misinformation: class adopting protocol MyProtocol can follow not rules nonatomic and copy.
And for me it's very odd add properties inside protocols. It is going against paradigms of object oriented programming: delegates shold do some action, not provide informations.
So I advice you not use 'a' and 'b' cases, but to think again about yours programm architecture.

How can I have a custom class inherit from multiple superclasses?

I have a an iPhone app in which class A is a subclass of UIViewController:
Now I'm creating a new app, in which I want to re-use A, but have it subclass from B, which is fine, because B subclasses from UIViewController:
But now I have another class, C, which is a subclass of GLKViewController:
The problem comes when I try to make a third app which re-uses B without any changes. Since B inherits from UIViewController, I need to somehow tell C that it should inherit from B and from GLKViewController, which I believe is a case of multiple inheritance:
From what I'm reading, the best way to handle this is with composition, but I don't understand how to best apply it to my situation.
As a stand-in solution, I realized I could just create a wrapper class D which I can then modify on an app-by-app basis to subclass from the appropriate superclass for the task at hand:
But that seems kind of hacky. Is there a better way to do this?
Objective C only supports single inheritance. In this case you'd probably want to use protocols for common functionality. You can use a helper object to implement the protocol methods. In this case, you're not interested in whether your object is a member of a particular class, but whether it implements a specific set of methods.
you can't do that in Objective-C is single inheritance -- like java or most of the other modern languages.
use a paradigm of composition or delegation
You could possibly get that covered by using a category. It certainly is not the same as multiple inheritance but sometimes does the job.
Let me draft an example for a category and see if that does what you aim for.
Header: UIViewController+MyAwesomeExtension.h
#interface UIViewController (MyAwesomeExtension)
- (void)doSomething;
#end
Implementation: UIViewController+MyAwesomeExtension.m
#implementation UIViewController (MyAwesomeExtension)
- (void)doSomething
{
NSLog(#"doing something totally awesome");
}
#end
Now you are using it from within one of your UIViewController subclasses which also includes like e.g. GLKViewController ...
Implementation:
#import "UIViewController+MyAwesomeExtension.h"
...
[self.viewControllerDerivedClass doSomething];
...
Note that such category does have its limits. To find out more, how about researching the subject a bit further.
Overall, I think the "most" correct answer would be using protocols to get as close to multiple inheritance as possible, as Mike C. drafted in his answer. My answer is mostly a workaround for simple cases.

Properties and ivars in MasterDetail template

After reading about properties and ivars in Objective C I'm still confused with MasterDetail template for iOS in XCode.
MasterViewController declares property for DetailViewController:
#class DetailViewController;
#interface MasterViewController : UITableViewController
#property (strong, nonatomic) DetailViewController *detailViewController;
#end
And ivar for array of objects:
#interface MasterViewController () {
NSMutableArray *_objects;
}
#end
Why is it that way? I just can't get why those two things are declared differently.
Thanks.
Declaring something as a "property" allows other objects to access and work with it. In The case above, adding "detailViewController" as a property to MasterViewController means other objects can access and work with the methods & properties DetailViewController exposes.
While the "_objects" variable is internal (or private) to the MasterViewController.
Apple's documentation is generally excellent. Apple's templates are... sometimes a little challenged. They are also sometimes slow to be updated as the language improves (or they are updated erratically). The objects array should really be a private property rather than an implementation-declared ivar. In any case, don't read too much into this.
Remember, the view controller shouldn't even be holding the data; it should be getting it from the model classes (which the template doesn't provide). Some of this is in order to keep the templates simpler to use (they're not actually example code; they're templates). Some of the weird code is due to limitations in the templating engine. (They didn't used to be able to prefix your classnames, even though they told you that you must prefix your classnames; it was very annoying.)
Unfortunately, seeing something in example code also doesn't necessarily mean it's a correct way to code. Much of Apple's example code would be completely inappropriate in production code (most of their examples lack proper model classes, or fail to handle errors correctly). But again, that's kind of the nature of example code. Focus on the coding guidelines. They're much more useful than learning from templates and examples.

"Proper" way to define a class - Properties vs Methods

This is an observation and a question:
I am loading some json data into a class (json already converted into an NSDictionary). The values will be read-only from the outside:
#interface Checklist
-(id)initWithJSON:(NSDictionary *)json;
-(NSInteger)checklist_id;
-(NSString *)checklist_name;
etc....
#end
With the corresponding method bodies in the .m file.
As a test, I created a class for another data element:
#interface ChecklistItem
-(id)initWithJSON:(NSDictionary *)json;
#property (readonly) NSInteger item_id;
#property (readonly) NSString *item_name;
#end
Functionally, the two classes have similar methods in the #implementation. In both cases they basically pull the appropriate value from the json and return the result. And as far as the rest of the program was concerned, the two approaches seem to be interchangeable.
So my question is:
Which approach is the best one to use?
I find either way equally readable and so far I can not find any code-reason to prefer one way over the other. I can kind of see the second option as nice since it kind-of documents the json.
You should use properties, they come in handy once you use KVO.
Also you can define public readonly properties and overwrite them in a class extension with a readwrite property that is only usable in the same class. If you try to achieve something similar you will have to deal with private helper methods — the code gets ugly.
-(NSInteger)checklist_id;
-(NSString *)checklist_name;
This isn't standard Objective-C naming. If you want to do things properly, follow the platform conventions. Apple document this in their coding guidelines documentation.
Which approach is the best one to use?
They are equivalent as far as Objective-C is concerned. The property syntax expresses your intent at a higher level than manually creating the methods, so I would prefer that approach. It's also less code.
This is less important now that ARC will clean up memory which would have been managed
inside the setter but this is still very much best practice. The performance overhead of
calling a setter method is also negligible compared to the safety gained from always
going through the setter.
this is a subjective question and you'll get nothing but opinions back, but here is mine:
the read only properties will just write the getters for you. if you don't write a private read write propertly in your .m file or wherever and just set the ivar's directly you don't even get the will/did change value for key calls and will have to call those yourself also.
#interface ChecklistItem ()
#property (readwrite) NSInteger item_id;
#property (readwrite) NSString *item_name;
#end
To access them KVO complient inside the object you'll have to do:
self.item_id = 13;
And not:
_item_id = 13;
Of course you could just have getter methods:
-(NSInteger)checklist_id;
-(NSString *)checklist_name;
And just wrap all changes in in your KVO methods:
[self willChangeValueForKey:#"checklist_id"];
_item_id = 13;
[self didChangeValueForKey:#"checklist_id"];
it's just a coding style choice, and sometimes leveraging what the compiler will write for you. but either option works the same.
If the values are read only, I'd think you'd want them as methods rather than as read-only properties to avoid any confusion that the values might be able to be set. Unless of course you want the subscribers to be able to use the dot notation for accessing the properties, but if you're just returning the values in the NSDictionary, the method form would be better as you're not keeping around another copy of the data.

Resources