Is there any reason why someone would want to create an Core Data model programmatically? - iphone

I wonder in which cases it would be good to make an NSManagedObjectModel completely programmatically, with NSEntityDescription instances and all this stuff.
I'm that kind of person who prefers to code programmatically, rejecting Interface Builder. But when it comes to Core Data, I have a hard time figuring out why I should kill my time NOT using the nice Xcode Data Modeler tool.
And since data models are stuck to a given state (except when you want to do some ugly migration operations where thinks probably go wrong and users get mad, really mad), I see no big sense in a data model that's made programmatically for the purpose of changing it all the time.
Did I miss something?

I dont think you missed anything. The only reason I can see to create your model programatically would be if the objects you are modeling are themselves dynamic: you could for instance build a coredata entity (or graph of entities) in response to a web service which changed over time, or was selected by the user. However, I think if you had that or a similar use case, you wouldn't need to write this question (and you'd probably solve it a different way anyway)

So, if your application is dealing with resources that are dynamic, as #Andiih mentioned, then this programatic is the only way to do it. I don't know what my core data entities are until runtime, I don't know what the attributes are, or what the data looks like. So, I ask the server to give me the kinds of resources I should support and what their attributes look like. I build the model, the entities, the properties, the relationships - at runtime. I still want to use Core Data because I'm dealing with a lot of data and I need the benefit of efficient memory management with NSFetchedResultsController, etc. I can only do this programmatically.
The trouble is how to handle migration to try and preserve as much of the persistent store as possible, to reduce the size of the networked data payload after the model changes. Right now I blast the whole model and the persistent store if there's a conflict. I haven't yet figured out a way to create an .xcdatamodel from a programmatically generated model, thus I can't yet create a version mapping to do the migration.

Everything is a trade off. Basically, I think IB and the visual Core Data modeler are the right tool if you're building a simple application. You'll need to make the determination when your application becomes large/complex enough that you prefer to have direct control over all aspects of the code.
Regarding Interface Builder, if you have an application with a variety of complex interactions between view controllers, and multiple custom controls, I find code more appropriate.
For Core Data, the question is pretty much the same. Does your project have a defined scope? Can you foresee everything in that scope being done within the visual modeler? If so, it's probably fine. For other projects, where you may be asked to add features on an ongoing basis, perhaps it's better to spend a little more time writing it out so you have more flexibility later.
One other thing to consider, that doesn't get mentioned much, is it's MUCH harder to ask for help with IB or any hybrid visual design/code system. When something does go wrong, or you need help, it's way easier to post your code, than try to explain what's going on in a visual modeler.

In general, there's no reason to build the managed object model in code. There's nothing you can do in code that can't be done in the model editor. There are some fancy tricks you can do in code, however, to work with multiple models. For example, you can merge two models, establishing cross-model relationships between entities in those models at load time (see Cross-model relationships in NSManagedObjectModel from merged models?).
Regarding whether it's a good idea to code or use the graphical editor, I think the balance tips heavily towards the graphical editor in this case. Being able to verify the model by visual inspection instead of (rather convoluted) code is a win. The model can still be verified by unit test, if you desire.

I have one use case that might be valid, what if you load some data from the internet whether it is XML from an RSS Feed or WSDL response, then flatten those responses into a tabular from generating an in memory data table and finally mash it all up into a single coherent data model, then you can create the entities for those in memory data tables and create master/detail relationships. That's one case I think Core Data data model generated programmatically could become handy and a powerful feature.

I've changed models programmatically in unit tests. For example, I wrote a class that is designed to work with Core Data models that have a particular protocol attached. Instead of testing against a random implementation, I mutated the default model by adding one just in the unit tests programmatically, and tested against that test-only model.

Related

Is Entity Framework also persistance layer?

OK. I know that Entity Framework is ORM. We use it for mapping data from database to object model, and from objects to relational data. But where it fits in a context of persistance layer? Can we say that persistance layer is also Entity Framework?
I would say - No! There are a lot of articles about this topic. But in general you don't want your object-relational mapper to be data-persistent. In fact exactly the opposite, keeping it persistent ignorant you can benefit by using your data classes with different types of data providers such as relational databases, web services, XML files and what not.
To keep data persistence you may take advantage of different design patterns like Repository pattern and Unit Of Work so you can really decouple you business layer from your data layer.
Ok, to make myself clear since it's very difficult through comments, here's an update to what I wanted to explain. Please have in mind that this is just my interpretation, and the way I'm using EF, I've been using it in different projects (desktop and web) but it's not universal, but still covers a lot of the most common scenarios.
So since I'm a big fan of Code First I'll write from this prespective. The Database Model is where your entities lies. Later on based on those entities the EF will generate your database. So what is important on this stage of development - you want to have you database normalized and you want all navigation properties set correctly. Not so trivial tasks as it may seems but that it's, you just care about how efficient your database will be.
Now comes the tricky moment somehow you should deliver you data to the business layer and it's true - as far as we are talking only about data from a database using repository is very arguable. However even then the one advantage that you get when having this Repository between the data and the business logic is that you don't have to take in mind the business needs while creating the data model, and after that this doesn't make it any harder to use your data from inside the business layer even though what exactly will your front end looks like at the time you create the database model.
So at this point let's consider again the example case where in you Database Model you have those two entities - Customers and Orders. When a user log in into your application and wants to see his orders you need to join two tables in order to provide the front end the information that it needs. Option 1 - you don't have a Repository and you are using the DbContext directly from the method that returns the data. That means two things - you gonna have to write the same code everywhere you need to get this specific piece of information and 2 - if the business requirements change and in the same view that since now was used to show a customer and his orders now you have to show some additional info which is taken, let's say from a third table, then what happens - you have to go to each place where you use this view and change the way you retrieve the data. And option 2 - you have Repository, all your methods for accessing data are stored there and the Business Layer is completely ignorant about the way it get's the data, the Database Model is also ignorant about the needs of the business model which lead to loose coupling and only one place where you gonna have to make changes if you have to. In the scenario above, if you indeed use Repository and in your repository you have method called GetUserOrders() and inside this method you make the database call, the joins and so on, and all that the Business layer needs to do to get the data in the proper way is call this method when the requirements change and you have to include one more table, this time you don't have to look for all the places where you are using this data, you just have to modify one method and that's all.
It's pretty much the same logic on the way back. When you have some complex data returned from your front end and you want to save/update the old data with the new one, again - you can do it from the business layer but it leads to the same problem as when you have to get data, instead - you just pass the complex data to another Repository method which knows how to deal with it (say maybe some of the data should be saved directly into database and other should be used to feed a web service or whatever scenario comes to your mind) and here again - when something change, like - you want to use more heavily web services or the opposite, you want to migrate to more database centric design, all you have to do is change the method that takes care about the data the is concerned with this changes and nothing more.
So even though when I'm writing this I can see that DbContext can very well act as a repository and in this regard also as a data persistent layer, there are still some valid reason to not let this happen. Especially right now when the web services are more and more popular, WebAPI2 is out and RESTFull services are frequently used I think that leaving the EF as persistent ignorant as possible is the way to go.
But yet again, this is my opinion. There are a lot of articles on this topic so I urge you to google and read about it, since I think this is very important part form the architecture of every application.
P.S
In response to your comment which was written while I was writing my edited answer:
If I change data source I need to make changes in DAL anyway or in my example in repostitory. - the answer is yes. But there is no way tho change the data source without changing the DAL. The question is how easy will be to do that. I think the with what I've written already you can decide for yourself which way is better but just because I really think this is one of the few really strong arguments of leaving the EF persistent ignorant all write it again. When you have Repository and there are methods which take care for data manipulation, every time something related with the way the data is fetched affects only those methods and nothing else. If you use the context freely, in your business layer even a little change may cause you a lot of trouble just because it always possible to miss something, you have to go through the entire code to make sure that you have fixed all places and it's just not as efficient as having all in one place.

Entity Framework without database

I like working with the entity framework for many reasons- the ease of use of the entity designer, the power of linq, and the ease of binding.
Occasionally I want to build a simple app that doesnt need to use a database, but still needs to work with data and display it on screen, in grids etc, so I'd like to just create a quick EF model and use it for this, but it doesnt seem to work very will with just using it for local data.
My question is- is there a correct usage of the EF for working with local data, and perhaps then just serialize/deserialize the whole context to a file? Or is this just too much effort to make work properyly? I used to use Datasets in this way, along with Linq to Dataset, and it works well... So perhaps those are still the better way to go for this scenario?
Yes you can use entity framework as local, and also access the data that is currently in-memory, read details as link below:
http://msdn.microsoft.com/en-us/data/jj592872.aspx
I don't know what you mean by "local data" exactly (sounds like it's not a database), but I think the Datasets vs. EF portion of your post is (for me) the real question.
EF is great when you need to model robust business logic, are implementing a Domain Model pattern, using Domain Driven Design, etc: basically any scenario where a Table Module or Active Record pattern is inappropriate.
When you just need to display some grids of data, and the business logic is very simple, Datasets are definitely the way to go (in my experience).

When to use CoreData in iPhone development

I've been looking into creating a new application for iOS and after my last few apps I've been tempted to use CoreData (for benefits including saving and automatic undo/redo).
I've been a little confused when trying to implement the data-model I've been given fr the project though, since it seems that CoreData seems very much much closer to a database than a data model.
Should I be using CoreData for an application that doesn't generally fit the 'large amount of data/records' description I would generally use an SQL style database for?
If it helps, the app I'm designing will be a sort of document editor, so there will be a number of objects I will need to represent (there might be embedded images, graphs/charts, hyperlinks etc within the document) and I need to create this model from an xml description.
Most of these 'items' need to implement a set of interfaces (the model was created for a Java product; I'm having difficulties seeing how inheritance and abstract interfaces can apply to CoreData), and every example I've found so far seems to add base elements (like an NSDate or String) to a simple model.
Does this sound like a candidate for CoreData, or is CoreData more of a tool for implementing a database in an application? (i.e a library system/staff database).
consider CoreData as an option once you are able to properly write the majority of the code it will replace. so once you know how to properly serialize/deserialize, write undo/redo, KVO, copying, etc.
Should I be using CoreData for an
application that doesn't generally fit
the 'large amount of data/records'
description I would generally use an
SQL style database for?
CoreData isn't restricted to large databases (at all) - it will work well with small sets, and beyond databases (binary files and documents, direct in memory use of models).
your example could benefit from CoreData. it depends on the amount of custom code you need - sometimes it is just easier to write the code if you're just using CD objects as an interface generator, and your app uses a lot of custom code/objects. to be honest, i've never used CoreData in a shipping app - i always found reasons to migrate models to existing code before then (assuming CoreData was also used during development/modeling stages).
it's a nice framework, but it shouldn't be viewed as a 'magic object generator' that will solve most problems. first, you need to understand he technologies/patterns you intend to replace with it. there is a limited number of ideal uses for it. if you can't write the code the objects depend on, don't bother using CoreData. iow - don't consider it as a replacement for initial effort because there are certainly times when it is a good choice and a bad choice - but you can't make an objective answer for your context if you don't (truly) understand what it is capable of.
One of the purposes of Core Data is managing an object graph in memory. This certainly fits your application. It can then be persisted to disk easily. Using a tool such as mogenerator allows you to use Core Data to manage the object life cycle, graph and persistence, but add your custom protocols on top.
In short, yes, you can use Core Data for non-database uses, with a bit of work to conform to the model.

Is there a forms builder for Cocoa?

As I have a complex domain model (DDD) where I need to create a few hundred forms in the user interface, I'm looking for a generator, preferably embedding the apple layout rules, and data binding. This is crucial to get a uniform application appearance.
I would prefer the generating to be of run-time instances (introspection), not static source code.
I do not want to build from a data model, as that doesn't have enough information to create something useable. I have information on grouping, validation, roles and rights, navigation, filtering, actions, workflow so I should be able to do much better layouts.
Even better would be the ability to also generate forms for the iPhone/iPad, using the default navigation.
[Results]
Sensible TableViews looks like the right kind of solution for iPhone. The descriptions are not yet sophisticated enough but provide a good starting point.
Interface Builder will do this for Core Data models if you option-drag parts of (or all of) your data model from the Data Modeler into a window or view in Interface Builder.
When you drop the managed object(s) you dragged, you're given an option to create a Single Item View, a Master/Detail View (with search and detail fields and add/remove buttons), or a Collection View (with box + search field).
I don't know of any third-party solutions to do this from "just any model." It'd be a great tool, but would likely require using an object model to define the entities (like Core Data's Managed Object Model).
Sensible Tableviews Might be able to help you. I haven't used them myself but it looks solid. It also supports generating forms from core data entities.
Maybe Echasoft Reports would work for your problem? (Plugin for Interface Builder that gives you easier reporting capabilities). I saw this demoed at NSConference, and it looks pretty awesome. Commercial, yes, but for 100+ forms it might be worth the money...

Tips for converting an iPhone 2.x app to 3.0 with Core Data

I have an app developed for iPhone OS 2.x. For the obvious reasons, the model classes in that app were written without Core Data.
Now that 3.x is available, I'd like to know what are some of my options for taking my existing model classes and rebuilding them with Core Data. I do many things with my models besides the obvious, such as serializing them and storing them into an sqlite3 database so that my application can work when there isn't any network connectivity. I would expect Core Data to be able to help me with that as well.
Also, with the incorporation of Core Data in your application, is there any reason at all to still use sqlite3? Would you still use it for things such as providing for offline content, keeping around statistics that might not necessarily make sense to create a model out of? Or is there ways of incorporating all of that into Core Data as well?
The primary benefits I've found from using Core Data in my iPhone applications are:
Keeping referential integrity
Managed model migration on schema changes
providing an object relational mapping
Vastly simplified insertion and join and query process - joins for instance are typically just done through "dotted" syntax
Multiple store overlaying (although look for my stackoverflow question about this to see if it actually works on sqllite, still awaiting response...)
Structured predicate construction - you can create your predicates as objects instead of inline embedded sql statements
Reflective data store - you can introspect the data store at run time in a structured and statically analyzable way
That said, if your app already has been designed to work against a sqllite database, you really need to ask yourself if you're ready to convert your application over.
You will need to do at least these things:
Remodel your entire database schema in Core Data managed object models
Rewrite all of your database queries and management to use Core Data
Rewrite all of your models to either be backed by Core Data generated managed objects, or extending them
Import all of your existing data by hand into your Core Data database
Be prepared for potentially writing a lot more code! Although Core Data provides a good object framework for dealing with data store querying and management, it also does so at the expense of verbosity.
To continue the previous point, when you do even relatively minor changes to your schema, you're going to be prepared to spend a relatively significant amount of time providing a schema mapping and applying it correctly to your existing schemas.
Give you already have solved almost all of these issues already, the benefit you would get form porting an existing application to Core Data is elegance and keeping up with latest technology. You will have to provide a not insignificant amount of effort to get that, and given the benefits probably aren't stupendous, you might find it not really worth your while.
To answer your second question, I can't really think of any reason for using sqllite directly if you are using Core Data to be honest. I'm not certain that outer joins are terribly simple in Core Data for instance. However, you don't typically use Core Data in that manner - you would use it procedurally to craft the same effect as the outer join in SQL.
For statistics and stuff I would still use Core Data because it provides some fantastic aggregation functionality.
Note there is nothing preventing you from taking the opposite approach: adopt Core Data for extended functionality until you become comfortable enough with it, then begin porting your main applications existing code to use Core Data.
The other answer is very good, but I disagree on the benefits being mainly elegance and keeping up with technology... the real reason to move to Core Data is actually performance and memory related, in the Core Data manages caching very intelligently and you'd have to do a lot of work to replicate that. That to me is the sole reason to even consider it, as it is very verbose as noted and you also have to work around all data objects needing to use NSNumber to hold primitive values (which I find particularly annoying).
For something like your setup, the approach I'd probably take for migration is to have each model class hold on to managed objects that are actually the storage classes - then your whole code would not have to change, just some things in the model objects and possibly management classes you might have built to handle creation or population of the model objects. That even hides the NSNumber wrapped primitive issue.
If you are strongly considering working with Core Data, you may want to take a look at this book that covers the iPhone specific Core Data as well (including NSFetchedResultsController):
http://www.pragprog.com/titles/mzcd/core-data
You can buy an e-book only unlocked PDF version which is not too expensive...