Sharing code between NSDocument and UIDocument - cocoa

I have created a document-based app that uses Core Data. I created the mac version first, and now that it's working properly, I am moving on to create an iOS version of it.
I just can't get my head around how to maximize code reuse between the iOS/mac versions, with respect to the Core data bit, since they don't use the same classes.
My document class that handles saving and such is a subclass of NSPersistentDocument. My intention is that a well-designed model class should work in both environments, especially since I don't do all that much fancy stuff with regards to Core data.
Now, since NSPersistentDocument isn't available in iOS, I hit a wall. I tried to get around this by using #if TARGET_OS_MAC and TARGET_OS_IPHONE and in that manner make it a subclass of UIManagedDocument in the iOS version. That obviously would have been convenient, but I can't seem to make it work like that. And it's really looks quite messy, since there are a lot of other stuff that has to be conditionalized as well.
I also tried building the classes atop of NSDocument/UIDocument instead, implementing the Core data hooks myself, but it also looks quite messy, leaving me thinking it's not the right way to go.
The question:
To me, it seems like a good idea to reuse the same document class between the iOS/mac versions, but maybe I'm being naive.
What's the best way to do this?
Should I forget about the code sharing and create a separate document class for the iOS version that emulates all the methods present in the mac version?

Am I right that the code you're wanting to share is model-related? I suggest refactoring that code to a separate object, which both an NSDocument and UIDocument contain (as rickster suggested above).
I use a DocumentRoot Core Data entity with its own NSManagedObject subclass, but if there are no properties you want to manage using Core Data, you can just subclass NSObject.
This may sound strange, but NSDocument and UIDocument are actually controller classes. (To be specific, they're part of the model-controller.) Their jobs are to load the model, set up windows, and save the model. If you need to provide an interface for higher-level access to model objects, it could be in a document root or model helper class instead.
Similarly NSPersistentDocument's job is to configure the managed object context and the persistent store and handle loading and saving. It doesn't necessarily need to provide a complete interface for accessing the model.

(Bringing this over from my comment.)
In general, the situation where you have two classes which must inherit from different superclasses but which also want to share a lot of code is composition. Put the shared code in a separate class; your NSDocument and UIDocument subclasses can each keep an instance of that class, and message it whenever they need to invoke that shared code. (Though as #noa mentions, you might want to consider whether all of that code belongs in your document class to begin with.)
Of course, then you might end up writing a bunch of methods that read like:
- (id)doSomething {
return [sharedController doSomething]
}
That can get to be a pain... so you might want to look into Objective-C's message forwarding system.

Related

How can i set the api version on a generic controller when loading a plugin?

I have some plugin's which are basically input and output type definitions. I have a generic controller which i can add to the mvc pipeline. All works fine.
but I'm having trouble setting the api version on this generic controller. I know you can set this based upon an attribute on top of the controller class. But since you can't have this dynamic (attribute) don't allow it, i have no way to set the version for each instance of the generic controller.
Currently i just compile the controller for each instance on runtime and register i using the roslyn compiler.
is there a way to set the api-version somewhere in the pipeline of registering controllers in the mvc pipeline and endup with different api versions endpoints.
This can be achieved by using the Conventions API. It was designed to support this exact type of scenario:
https://github.com/microsoft/aspnet-api-versioning/wiki/API-Version-Conventions
This will only work on closed-generics, but it shouldn't be too much work to make that happen. Here's a couple of basic examples:
// typed, closed generic
options.Conventions.Controller<GenericController<PlugIn1>>().HasApiVersion(1,0);
// untyped, closed generic
var controllerType = typeof(GenericController<>).MakeGenericType(new []{typeof(PlugIn1)});
options.Conventions.Controller(controllerType).HasApiVersion(1,0);
You can also author your own custom conventions a la IControllerConvention. This approach could be used to version all controllers that inherit from GenericController<>. Then you just need to add it to the conventions like this:
options.Conventions.Add(new PlugInControllerConvention());
Hopefully that's enough to get you started. Feel free to ask more questions.

MVC 3/Design Patterns issue

I made a settings page for my website. On this page the user is presented with a bunch of site wide settings they can manipulate. I made it so when the user selects a setting the page will automatically run an ajax request to send the setting to the database. My question is in how I do this.
At first I just did calls to the repository. One call to get the data back, put it into a ViewModel then give that ViewModel to the View and the ajax controller just sent the settings back to the database. This way seemed like the best at first especially for unit testing purposes since I could just pass in a fake repository if needed. Then for the user to get a setting they just called the repository and pass in the setting name they want.
Then I had a bright idea. I made a singleton class called SiteWideSettings and each possible setting on the site was a property of the site. When SiteSettings is called for the first time all of the settings are loaded. When Set is called on any of the properties it will call the repository function to send the setting. Now with my Settings view I'm just passing in SiteWideViewOptions.Current and on the ajax call I'm updating the property that was changed. This is working for me however it's not very unit testable since I can't really pass in a repository to a singleton's constructor since its constructor is private. What I currently have is working fine but I just don't feel like it's the best solution and unit testing isn't really possible here.
I'm thinking of one of the following but not sure which is the best.
Add a Repository property to the SiteWideSettings class
Add a function to the SiteWideSettings class to pass in a repository
Not use a singleton for this at all and just go back to what I was doing before I had this idea
Any comment on this would be greatly appreciated.
Note: I know. I know I'm doing unit testing wrong in this case because I didn't write my test first so please don't scold me for that.. I have already scolded myself and with my next task I won't do it again I promise :)
"Then I had a bright idea. I made a singleton class called
SiteWideSettings and..."
This sounds like a bad idea. Let your database be ground-truth for what the settings are, not some in-memory cache that you now need to keep up to date. Let your ORM do caching if you need it for performance otherwise you are just adding problems especially if you now try to run your site on more than one server.
If you want to simplify the controller so it has less 'set-up' and 'tear-down' code in it, use an IOC (e.g. Autofac) and inject any dependencies you need (e.g. a DataContext or a Repository) on a per-http-request basis.
Your action methods are now easier to test since you can simply instantiate your controller (injecting the dependencies manually using its constructor) and then call your method.

Calling protocols from a framework?

I am currently using the NinevehGL engine to develop a simple app. This engine has a class called NGLMesh that stores openGL data for an instance of this class. From NinevehGL's documentation for the copyInstance method located at http://nineveh.gl/docs/Protocols/NGLCopying.html it says:
"The NGLCopying is an extension of Cocoa protocol NSCopying.
It defines two basic copying modes to NinevehGL objects:
Copy: Makes a new clone, copying all the used memory.
Copy Instance: Makes a new clone, but clonning just the superficial memory."
I would like to copy one of my NGLMeshs into a new NGLMesh instance using this method, however Im having a hard time understanding protocols and how to call them. Could someone offer some explanation? The internet has proved to be a little confusing thus far.
From what I gather (although Im most likely wrong) I need to "adopt" the NGLCopying protocol in the class that I want to use it with. I cant seem to find much information on how to accomplish this.
A protocol is just a list of messages that a class can respond to. Think of it as an extension of the class's #interface block, only it can be shared by several classes. If you are just trying to copy another class that already conforms to this protocol (such as NGLMesh), you don't need to do anything special — just do [yourNGLMeshObject copy] or [yourNGLMeshObject copyInstance].

should I be creating my objects manually or with InterfaceBuilder?

I am relatively new to Cocoa/Xcode and am not sure if I am structuring my application in the most "correct" way possible. I have a number of objects which are active the while time that the application is running. Should I be creating these objects manually or with Interface Builder?
The type of objects I am referring to:
"downloader" which is responsible for downloading files to disk
user interface updater which is responsible for updating the user interface to show the results of the downloaded file
Should I create these objects in IB and set up the connections between them with code?
It's really a matter of personal preference.
In my opinion IB only really good at laying out views, so I tend to only use IB for my view and my view controller, and I create everything else in code in the view controller's viewDidLoad or init method.
In your example, connecting the "downloader" object directly to the interface seems like an MVC violation, so I would keep the downloader out of my xib.
The "interface updater" would be connected tightly to the interface, so it could be in the nib, although unless I had a good reason not to I would probably just put that code into my view controller class.
If you are creating things in code, note that viewDidLoad/viewDidUnload can potentially be called a number of times, as the os loads and un-loads your views when they are not visible to save memory. So only put transient objects there... things that must exist for the life of the view controller should be created in the init/dealloc methods. Part of why I like to do most of my object creation in code, is the finer level of control you have over memory.
I typically build as much as I can in IB, and then switch to code when I run into the limitations of IB. It sounds like you should be able to create the UI you described in interface builder.

NSArrayController and referring to a shared, static, Core Data based library

Using this guide I have created a static library (let's call it AppCore) that can be shared between the Mac OS X and iOS versions of one app. This static library uses Core Data and the point of it is to share the model part and schema versioning between different implementations.
I created a NSPersistentDocument based project that will depend on this AppCore. In this project I added a reference to the .xcdatamodel file. Then I created a simple table view with add/remove buttons to edit an array of one entity type with the assisted "new core data entity" item. This created an instance of NSArrayController and the required bindings for the add/remove behaviour.
Now, everything seems to work fine when I'm using the default class for the Core Data entities (NSManagedObject) and I'm able to add new rows using the +/- buttons. However, when I change the entity implementation class to a custom one, I'm getting an error
Failed to create new object
This seems to come from the NSArrayController and it seems to be unable to instantiate the required entity. I can, however, create one in the NSPersistentDocument subclass by:
[NSEntityDescription insertNewObjectForEntityForName:#"SomeEntity" inManagedObjectContext:[self managedObjectContext]]
What confuses me is why the instance of NSArrayController can't. If I understand correctly, the array controller is instructed to create an entity, not class and my guess is that the entities are created with the help of NSEntityDescription class. I could implement my own version of the array controller's add: but then again, it might be that here something is fundamentally wrong. I haven't touched the init:s and the custom entity class implementation is simply for convenience, to access the attributes directly.
I have tried changing the base SDK on the AppCore but without effect. Currently it uses the iOS version but I'm not sure how it should be. This is another question but if unrelated, I might ask it here on a separate question.
So, to summarize, why can't the NSArrayController create an instance of this entity?
Thanks in advance.
Update
This works if I add the SomeEntity class from the AppCore to the dependent project as a reference. This is not the most usable way since modifications to the AppCore has to be propagated to the dependatnt projects also.
Bingo. I missed the "-ObjC" flag for the dependant project's "other linker flags". Now everything works like a charm.

Resources