IOS ManagedObjectContext Placement - iphone

I am writing an application which needs data persistance. I am using CoreData as my framework for this. I am currently trying to design my data structures for the app, of which I am planning on having 2.
The main data in my app is a sheet of various information which is input in a wizard format. I wish to use a MutableArray to hold the form data.
Secondly, I wish to have an individual instance (singleton) of MyClass available at any time, which I will use as a temporary placeholder to accept data being input during the wizard. Once the user completes all the steps, it will create a new object in the array for it.
What I gather from CoreData is that I need to use the ManagedObjectContext as a bridge between my application and the disk on the iOS Device. My question is:
"Should I use one instance of this context in the app delegate and just reference to it from any view who needs to talk to the files, or do I make a new context on every ViewController."
Right now I am not fussed on memory efficiency, but I wish to be as efficient as I can before I release the app.

If you have a singleton Shared instance as an access layer, you could also make it to be the communicator to your core data context.
I recommend using a UIManagedDocument to setup the managed object context. It is a bit more work at the beginning but for example you could implement iCloud access more easily.
But you can of course also just hold a managedObjectContext (without managed document) in your singleton, or - as in the per designed core data app - in your app delegate (which you can access by the uiapplication shared instance from anywhere).
There is really not one right way, I think. You could look at the Stanford c193p lectures (available on iTunes) and watch the core data sessions to get to know the managedDocument approach.

Related

Most efficient structure of an iOS app

Im developing an iOS application and I'm stuck on how to design the structure of it. Here is what I have so far:
The app is called "Time Clock" and it allows users to clock in and out. The app will generate time stamps when a user clocks in or out respectively. As far as data goes, I already have a large MySQL database that is already being used for a similar Windows desktop application. (I'm trying to cater to my company's iPhone users)
My question is, what should I do about the data structures in this app? Can Core Data retrieve the MySQL data (through a web service) and manage it? Should I use data controller classes to manage the data? I don't know the best way to handle the data.
Here are the data fields that need to be managed:
Store
Name
PIN
Timestamp In
Timestamp Out
All in all, what is the most efficient way to manage the data in an app such as this? If you could point me in the right direction i would be very thankful! :-)
Core data wont be able to retrieve anything from a webservice, you need to make a data access layer that will return that data to you via NSURLConnection and the like, there is a lot of information out there on how to do this... I would recommend modeling some classes that basically your data layer will fill for the rest of your application to work with. Also if your data is shared across many views i would suggest making some singleton class that will keep the data already retrieved, this way you can access it across different UIViewControllers in your application. Way I would structure this is
DataAccessLayer (layer that consumes your webservices, and fills the info into classes (your model)) -> Some Singleton class that keeps your objects from your webservices -> UIViewControllers (these will talk to your data access layer/ Singleton class for the data it needs which in turn uses it to fill your views ->VIEWS - > if changes occur to your model relay that to your webservices via the data access layer
... As far as core data, you can use that if you want to persist the data in your application, but its not necesary otherwise, i should point out that core data is not the only way to persist data in your application... This answer is a bit general but hope it can point you to the right direction..
Daniel

iOS Core Data: Confused about Core Data and database

I am really confused on what the Core Data actually is. Or I guess my question is, when dealing with a database, would you use Core Data? Like if I wanted access values from a database would I be using Core Data to access those values? How would I approach this problem?
Thank you so much for the help.
Core Data is an framework that does the work of "object persistence". In other words, it's code you can use that takes care of saving a collection of objects to disk and loading them again later. It does a lot of work to allow you to store lots of data and load only the objects you need at a time, and unload ones when memory is tight.
Core Data can use a database to accomplish this, but that's it's business, not yours. When you use Core Data, it is a black box. You tell it to save the data and then step out of the way.
If you want to interact with an existing database, such as a MySQL database on a web server, that's a completely different matter. You might use Core Data to store local copies of objects on your device, but in that case Core Data won't care that the objects are copies from some other database. It doesn't care.
It is a convenient, native means of storing data in your iOS applications. Don't think of it as sqlite although you can view the files it creates with various sqlite tools. Instead think of it as a tool for manipulating an object graph of information important to your app.
I've used it in two main ways. First to store a bunch of static data that is important to an app, in one case that was a large amount of location data for an indoor mapping application. What arrived as a massive CSV file of waypoints was converted to core data. Core Data was incredibly useful for this because it allowed preparing a sqlite file which was shipped with the application containing all the infomation. Updates from a web service arrive as more CSV that is added to the Core Data to keep information current. At runtime the location information object (the waypoint a user is at) is retrieved with a predicate (i.e. the point they tapped on) and that object, through its Core Data relationships, indicates where it is possible to go from that point. Core Data provided the information necessary to perform A* routing through the indoor map.
Second it is great when you have a bunch of objects arriving as JSON and you want to be able to store and access those objects later. Let's say you have a typical app where you have a User and some information about the User, let's call it Thing. Users have Things. When you want to know something about a User you retrieve the Core Data record using a predicate - typically "name" or similar - and you get all the information you stored about the User back. Again you can make use of relationships to explore the user's connections and make displaying information easy. Perhaps the User has many Things, then you can say "user.things" and you get a NSSet of NSManagedObjects representing those Things.
You use it like a database. Its utility is that it is easy to access from anywhere in your iOS code, it is easy to store and easy to retrieve information also. Faulting lets you retrieve one object and navigate to any object connected through relationships by following the relationships. Because you define the attributes and relationships yourself in the data model editor it is easily customized for what you need to store. To me it is one of the most used and most useful parts of iOS.
When you want to automate display of information from Core Data you can use a NSFetchedResultsController to initiate a fetch and to respond through delegate methods to changes to the underlying data. If you set up a UITableView to use a NSFetchedResultsController as data source, you can have the table automatically update whenever the objects displayed in the cells changed. Very useful for apps where you periodically update information and want what is displayed to be kept current.
When your object model changes it is possible to maintain all of your existing information and migrate it to the new model. Core Data manages automatic (lightweight migration) when it can, or if you have made more radical changes you can supply rules to handle the migration.
The limitation of Core Data is that it is not great for storing binaries. If you have images that you need to store, far better to store a path to the location of the image than trying to store the actual data.
Yes, if you want a local database on your device, Core Data is the appropriate technology. It probably makes sense to start your research with the Core Data Programming Guide.
You can alternatively use SQLite (which Core Data uses in the backend), but Core Data offers some material advantages and is the preferred database interface for iOS. If you decide to pursue SQLite for any reason, though, I'd suggest you contemplate using the FMDB Objective-C SQLite wrapper.
But Core Data is generally the way to go.

Iphone, for regularly updated data is NSUserDefaults still the easiest option?

I have been designing my app to store local user data which is changed / sorted and referenced regularly to be stored as global variables held by the app delegate and referenced through:
appDelegate = [[UIApplication sharedApplication]delegate]
Which seems to work though is most likely not best practice, is there any downsides to just holding the same data in NSUserDefaults, SQL Lite seems a bit heavy for my needs considering the data itself is a couple of small arrays of custom objects and is refreshed on start up and throughout the app.
Is there a general best practice for local storage, or does it really depend?
I recommend using Core Data. Although the first experience may be a little confusing, the investment will be worth it.
What you're doing is fine. A better practice would probably be to have a singleton class that contains all the related data. Then anywhere you need the day you just call [[globalData instance] arrayOfData] and have it. That way you abstract the data from your app delegate into a centralized place.
NSUserDefaults is used to store information between app launches. Use it to store settings or things that you read each time the app launches or use it to save the state of the app so a user can relaunch and be in the same place after they exited. There isn't really any noticeable performance issues unless the data you are storing is rather large.
for my needs considering the data
itself is a couple of small arrays of
custom objects and is refreshed on
start up and throughout the app.
As your current requirements are limited to small arrays and custom objects, NSUserDefaults could be used.
But while using NSUserDefault we should take care of these two facts.
1.) For custom object you will need to use Encoding Protocols for directly saving them using NSUserDeraults.
2.) NSUserDefaults some times shows strange behavior if we don't synchronize it properly. you can use its `[NSUserDefaults synchronize].
Core Data should be used when you are working many with interrelated custom objects. Because its concept of object relationship mapping and direct object management is quite good.{at lower layer it uses SQLite}.
SQLite on the other hand is relatively easy to implement and has C api for interaction with system. Here you will need to break down custom object into attributes and run queries.

Adding Core Data in Universal app?

I'm trying to add Core Data to an app that loads news form of an RSS feed so I can store articles offline. I am using ASIHTTP to load the data off of the internet as XML.
I'd like to store the articles in Core Data so I have them the next time I start. My AppDelegate_shared already is set up for Core Data, based on the template, but I'm not sure where to add all the rest of the code.
I found a tutorial by Ray Wenderlich, but it only confuses me. His tutorial assumes that there is a single App Delegate file, not three, as created by the Universal App templates.
Where in my three AppDelegate files (the shared, iPhone and iPad specific) does my core data article entry code go?
Are there any tutorials that deal with Core Data with the newer app template setup (3 delegate files)?
How do I read out my Core Data into a UITableView?
The Core Data stack only needs to be created in one shared location at startup. You can still have three different application delegates, as long as all three call the same setup routine. This could be done by making all three application delegates you have be subclasses of one base application delegate which handles this setup.
Another way to approach this might be to create a singleton for managing your Core Data access. See this question for other potential configurations that people have used, as well as the reasons for them.
As far as how to populate a table view with data from a Core Data database, you'll want to use NSFetchedResultsController for that. It makes displaying and updating table views simple on iOS. Jeff LaMarche has some good template code for dealing with this, and the sample applications generated when creating a new navigation-based Core Data iPhone application show this in action.
Finally, I taught a class on Core Data last semester (and finished another one last night), for which the course notes are available here and the video can be downloaded from iTunes U.
the core-data stuff belongs to the shared appdelegate. because the other two appdelegates are just subclasses of the shared one.
why not create a new universal project with coredata and look how it's done? and to see how the data is feed into a tableview, you could create a navigation-based project with coredata and look how it's done in there.

New to Core Data for iphone

I am new to the iphone platform and am creating an app that retrievals a rss feed and displays it in a UITableView. I have gotten this working perfectly (or rather, the way I wanted). What I was thinking was I would store the current feed items on the phone so that it would initally load the old items it has stored while it got the new feed, then parse the new feed and add the new items and refresh the TableView. I was going to use Core Data to store it the old feed items because it would be a good way of learning Core Data and it would be an appropriate use of Core Data. However, I am having a difficult time learning how to use Core Data and connecting it with the Table/Array.
I have already googled and looked on stackoverflow for tutorials but have yet to find anything that explains it in a way I really understand. Any explanation of the overall steps that it takes to add Core Data to an existing app would be greatly appreciated. Full-blown detail are not necessary (but would also be useful). I'm just not very experienced with SQL or storing of data in such a manner and am having trouble wrapping my head around how the whole concept of Core Data works and how it connects to everything.
Also, any better method of doing what I'm trying to accomplish would also be appreciated.
There exist Xcode templates for Core Data-based applications; these are a great start to getting Core Data off the ground. However, it sounds like you want to integrate Core Data into your existing app, so you'll need to...
Add three main Core Data objects: the managed object context (MOC), the managed object model (MOM), and the persistent store coordinator (PSC). These need to be accessible wherever you want Core Data available, so either in your app delegate or, more preferably, in the controller or data source for your table view.
Create a MOM in Xcode. This will be a file of type .xcdatamodel, and it's an object graph that defines all the Core Data entities you want in your app.
Use NSFetchedResultsController (as suggested by Louis Gerbarg) to get data out of Core Data and display it into your table view.
Add code in your existing RSS-fetching-and-parsing routines to store new Core Data objects back into the store, when appropriate.
A good way to start is just to create a new Core Data application and play around with it a bit; you can also look at Apple's fantastic resources on the subject, like the Core Data Programming Guide and the sample apps Recipes and Locations. (Developer registration may be required.)
One last thing to note is that for the most part, a lot of the Core Data code you need to add can be ripped straight out of one of the Xcode template apps and pasted into your program (this holds especially true for the accessors for the three Core Data objects you need). Be careful not to use code you don't understand, though.
If you are using CoreData to populate a UITableView you really want to use NSFetchedResultsController as opposed to trying to populate and sync array yourself. The documentation for NSFetchedResultsController includes links to several CoreData tutorials, including onces that populate table views.
NSFetchedResultsController is still a bit buggy and requires fragile workarounds. I would start with the simpler iPhone Core Data "location" tutorial before moving on to the Books tutorial.
Also, any better method of doing what I'm trying to accomplish would also be appreciate
yes, it sounds like Core Data might be overkill for your application. Assuming your feed items are stored in a collection object you can easily use OSX's built in serializaition.
Been noted in other Stack-Overflow posts, but I can highly recommend the Prag Prog book "Core Data: Apple's API for Persisting Data on Mac OS X" - most is also relevant to iPhone Core Data apps; there is a whole chapter on creating an iPhone app too.
http://pragprog.com/titles/mzcd/core-data