Can NSManagedObject class objects be used as models? - iphone

I have a bit confusion in choosing whether to use NSManagedObjet class objects directly as models or whether to create separate classess for models and create data mappers to map data from these model class to NSManagedObject class objects.
Is there any harm in using Core Data objects as models ? What are the pros and cons of both approches?
Thanks in advance,
Regards,
tek3

I read your question and I take it you are not asking whether to use NSManagedObject directly or whether to subclass NSManagedObject, but if you should have your model as separate classes which use Core Data by explicit methods written by yourself.
Core Data is designed to act as the model layer for your application. I do not see any real benefits in having your own model classes, writing an interface for them and implementing it in core data behind the scenes, unless you really need the freedom to give up core data entirely at some point.
I recommend you create your model classes as subclasses of NSManagedObject. You are free to extend those in any way you deem necessary beyond what core data provides you, but at the same time your model classes will have full benefits from the core data framework: faulting, caching, data integrity assurances, cascade deletes, etc...

If you just use NSManagedObject, you will not have the benefit of the convenient "dot.notation" when referring to attributes and relationships.
Also, you will have to retrieve all values with valueForKey and set them with setValueForKey followed by strings. This can be extremely error prone and cumbersome and the resulting code is not nearly as readably as with the dot notation.
Finally, in your object classes you can implement all kinds of additional functionality. Where would you put this code otherwise? Remember the principle of encapsulation that helps produce independent and reusable code.

Related

Do Core Data objects replace standard class objects?

I'm getting into Core Data and have started making "Classes" out of entities. Do I use these classes based off of entities as regular classes with methods etc?
Normally if I was using SQL directly I would have classes for each of my database objects (Tables) that store the working data and perform their functions.
Is this the same with Core Data - do I use the entity-based classes (subclasses of NSManagedObject).
So I might have these entities: Business -> Departments -> Employees
To comply with Core Data - do I make one class for each of these subclassing NSManagedObject and then add methods to it accordingly (like I would an NSObject class)?
Yes, you usually use the Core Data generated classes. You usually don't add methods to those classes, instead you should put them into a Category. This is because if you change an entity, you need to regenerate the class which will erase any methods that you added.
Yes(ish). They are your model classes. You aren't creating them 'out of' entities, they are the code representation of your entities.
You should have one class per entity, but you shouldn't create them yourself. You should get Xcode to create the classes. Or, better yet, use mogenerator.

Using core data generated classes as model objects ...?

Its more of a best practices sort of question. Here it goes...
I have automatically generated some classes for my entities in core data , now I want to use them as model objects to convert those models in JSON and send it over to the server. So my question is whether it is ok to use these classes or should I create separate classes and use a data mapper class to map these core data and model classes...
Which is a better approach and why...?
Thanks for your inputs...
You can use your NSManagedObject subclasses and add methods to those classes as you would any other NSObject class. This is perfectly acceptable (and would be better practice than to create separate object classes and using data mappers).
Use mogen to avoid the problem mentioned by #svena. It will automatically manage generation of core data models to prevent overriding your own code. Also I would suggest trying RestKit for server interactions. At least you can borrow their object serialization code because it does exactly what you want.

Adding exsisting classes to core data model

I have a iphone application in which I use nsecoding for saving my objects. However it has been decided that it should be saved using core data.
The questions is - what is the best way to convert my exsisting model classes to datacore classes. Should I create a new thorugh the xdatamodel editor and replace the old or what is the best strategy. I have not figure out an easy way to do this :P
Regards
Bjarke
Roughly, what you will need to do is this:
Create a data model that reflects the classes that you have already created - and I think you'll have to do it by hand in the model editor.
Then change your classes so they become subclasses of NSManagedObject. You'll have to make sure your properties are restricted to types handled by Core Data, of course.

What, if any, are the negative consequences of basing a Model layer on NSManagedObject?

I've been doing iOS now for about two years and mostly by consequence of simple data layers (no real need for ID's, joins, complex queries, etc), I've always managed persistence manually by extending NSObject, conforming to NSCoder, and saving my data in flat files.
However, now I am in a position where I need to start doing more complex query work and I am digging into CoreData.
My hangup right now is with NSManagedObject. It's a pretty intimidating class and I am wondering if there are any unwritten gotchas I should be aware of that might restrict my freedom while building a sophisticated application.
For example, things like #dynamic getter/setters are not to clear to me, etc
So:
1) Are there any features of NSManagedObject that would prevent me from handling instances of custom classes just as I would with NSObject?
2) Does NSManagedObject have any unusual behavior when objects are handled WITHOUT the presence of a ManagedObjectContext?
3) Can I supplant a #dynamic property declaration with my own custom getter/setter without too much pain? I use a lot of custom setters to enforce business logic.
and so on, and so on.
Thanks
Beware!
Core Data is not lightweight. It will require a lot of changes to the way your objects work, unless they are very basic.
1) Are there any features of NSManagedObject that would prevent me from handling instances of custom classes just as I would with NSObject?
Faulting and the lifecycle of managed objects are a little tricky to understand. Your objects can be "faulted" almost at any time (each iteration of the event loop anyway), which makes them lose any non-persistent state. When they get "un-faulted", they don't have access to anything outside the managed object context to restore their state. It's very hard for managed objects to access anything outside the managed object context.
Transient properties are possible, but are pretty much limited to things that can be computed from the persistent properties, since their state will be lost if the object is ever faulted. You also have to formally declare that you're using a transient property in the data model. Trying to just set up instance variables will run into problems.
So basically managed objects properties all must be persistent or related to persistent properties. Look at the objects you're planning to make managed. Are all their instance variables feasible and desirable to put into a persistent store? If not things will not be straightforward. You probably set up your instance variables in your init. There is no init that gets called every time your program runs for managed objects. There are awakeFromInsert and awakeFromFetch, but those don't work exactly like init. Your code calls init and can pass arguments. The framework calls awake and it gets no parameters.
Threading is another issue to consider. A managed object context, and therefore the managed objects in it, are recommended to be used only by a single thread. If you have multiple threads, and they need to access your model, you need to create duplicate managed object contexts containing duplicates of your managed objects. Core Data is designed to handle that without putting too much strain on memory, disk I/O, and processor, but it isn't lightweight from a coding perspective.
2) Does NSManagedObject have any unusual behavior when objects are handled WITHOUT the presence of a ManagedObjectContext?
You cannot have a managed object without a managed object context.
That's not usually an issue. Managed objects carry a pointer to their managed object context. It can be a little limiting though. If something outside your model needs to create a model object as an input to your model, it needs to have access to the managed object context to do that. Hopefully that would be through some kind of abstraction layer so it doesn't need to know it's dealing with Core Data, but you can't just give it a class and have it alloc/init. It is also a bit of work to move managed objects between different managed object contexts.
3) Can I supplant a #dynamic property declaration with my own custom getter/setter without too much pain? I use a lot of custom setters to enforce business logic.
Yes. It's a bit complicated but doable. You write your own accessors. In addition to your business logic, they must call key-value observing methods like willChangeValueForKey:. Then you access the data using primitive accessors.
1) Are there any features of NSManagedObject that would prevent me from handling instances of custom classes just as I would with NSObject?
Creating and removing them is different, but not difficult. Otherwise, no
2) Does NSManagedObject have any unusual behavior when objects are handled WITHOUT the presence of a ManagedObjectContext?
I'm not sure what you mean, you can pass a managed object to another class and use it quite happily without the other class knowing about the context, but you must have a context somewhere.
3) Can I supplant a #dynamic property declaration with my own custom getter/setter without too much pain? I use a lot of custom setters to enforce business logic.
Yes, NSManagedObject is designed for this purpose. There are plenty of examples of overridden accessors in the core data programming guide - there are some rules you need to follow but they are not too onerous.
Core data is primarily a persistence framework rather than a query framework - I imagine once you get into it you will wonder why you were wasting your time on all those NSCoding implementations...
1) Are there any features of NSManagedObject that would prevent me
from handling instances of custom classes just as I would with
NSObject?
No. You can extend a NSManagedObject subclass just like a NSObject subclass.
2) Does NSManagedObject have any unusual behavior when objects are
handled WITHOUT the presence of a ManagedObjectContext?
The #dynamic directive will create accessors optimized for saving in a persistent store managed by a context. The values will still be available just like any other object but you will generate a lot of overhead.
3) Can I supplant a #dynamic property declaration with my own custom
getter/setter without too much pain? I use a lot of custom setters to
enforce business logic.
You can but you will incur some performance penalty because the generated accessors will be highly optimized for the specific code in your app.
One major point of novice confusion with regard to managed object is missing that the generic NSManagedObject can represent any entity in the data model without subclassing. NSManagedObject has "associative storage" which basically means that it has an open dictionary attached to it that save any key-value pairs. When you you insert a generic NSManagedObject into a context, the keys of the associative storage "dictionary" are set to the property names of the entity given.
Therefore, you are actually never really forced to subclass NSManagedObject. Doing so is largely a matter of convenience.
That is why you sometimes see code that uses generic NSManagedObject and the setValue:forKey and other times you see custom subclasses that use anObject.propertyName.
I would also advise that if you find yourself using or saving managed object outside a context, then chances are good that you have a bad design.

ZF models correct use

I am struggling with how to understand the correct usage of models. Currently i use the inheritance of Db_Table directly and declare all the business logic there. I know it's not correct way to do this.
One solution would be to use Doctrine ORM, but this requires learning curve and all the current components what i use needs to be rewritten paginator and auth. Also Doctrine1 adds a another dozen classes which need to be loaded.
So the current cleanest implementation what i have seen is to use the Data Mapper classes between the so called model and DbTabel. I haven't yet implemented this as it seems to head writing another ORM. But example could be something this: SQL table User
create class with setters, getters, business logic here /model/User.php
data mapper /model/mapper/UserMapper.php, the funcionality is basically writing all the update, save actions in here.
the data source /model/DbTable/User.php extends the Db_Table_Abstract
Problems are with relationships between other models.
I have found it beneficial to not have my models extend Db_Table, but to use composition instead. That means my model 'has a' Db_Table rather than 'is a' Db_Table.
That way I find it much easier to reference multiple tables in the same model, which is a common requirement. This is enough for a simple project. I am currently developing a more complex application and have used the Data Mapper pattern and have found that it has simplified my code more than I would have believed.
Specifically, I have created a class which provides all access to the database and exposes methods such as getUser() etc.. That way, if the DB changes, or my client wants something daft like storing records in XML or we split the servers or something I only have to rewrite one class.
Again, my models do not extend this class, but have an instance of it assigned as a property during construction.
I would say the 'correct' way depends on the situation. Following the YAGNI and KISS principles, it is not good to over-complicate your model setup unless you really believe that it will benefit you in the long run.
What is the application you are developing? How is your current setup of extending Db_Table holding you back?