Where to use and initialize UIManagedDocument - iphone

I am new to IOS and I am following CS193p Stanford's lecture to learn about Core Data and in the demo the Professor used a category with somehow similar to what actually to if we check core data application checkbox while creating application and it puts the core data stuff in appDelegate. That's what professor did in demo he created managedObjectContext in AppDelegate and used a Notification to Pass the Context to controller. Now for Assignment he asked to use UIManagedDocument but I am confused about where to put it. Should I declare it in the View Controller or in AppDelegate and pass context using Notification Centre. So I just want to know which one is better for UIManagedDocument. S

Best way I found is create a new project (just as a sample), check 'Use Core Data' when asked, and look inside the AppDelegate. Use that to see how it's done and possibly, copy the appropriate parts (some adjustments will be needed of course). But mostly, use it to learn how Apple recommends it to be used.
Create a custom class with a shared instance that has managedObjectContext property.
In your application didFinishLaunchingWithOptions in AppDelegate, create your sharedInstance and pass it the 'managedObjectContext`.
MyDataManager *dataManager = [MyDataManager sharedInstance];
dataManager.managedObjectContext = self.managedObjectContext;
Notice also that if you terminate the app by hitting the 'Stop' in Xcode, the data won't be saved (since it's done, as it should, when the AppDelegate is about to close the app properly).
Make sure to also have [self saveContext]; in applicationDidEnterBackground, it supposed to be inside applicationWillTerminate as well. It is a good practice to write the database to memory only when needed (and not at every change). In the AppDelegate, it also ask if the data has changed before committing.
Of course, you can also save manually if you have the managedObjectContext instance.
If you made changes to the database you might have to delete the app from the simulator before running again (otherwise app will crash since the older DB won't match the new one).
Edit: I can't remember where I read it, but the professor does not use CoreData as a database pre-se, only to manage data (images etc.).

You can initialize your UIManagedDocument where ever you want to initiate access to your database. When I did the assignment (last year), I put in the AppDelegate. In glancing back now I see there are two ViewControllers in a UITabBarController and they both need the context. So I used the NSNotification mechanism like Paul did in lecture.
The reasons he gives for using UIManagedDocument over "User Core Data" checkbox (when creating the project) was:
It was simpler for him to explain (UIManagedDocument takes care of lots of complexities)
UIManagedDocument puts you on a fast track to using iCloud
I was just reviewing this as well. If you want to hear from Paul, he talks about it in Lecture 12 (Fall 2013-14) at 14 minutes and 25 seconds (UIManagedContext) and at 14:50 he starts talking about the two ways to get the UIManagedContext -- being UIManagedDocument or the "Use Core Data" checkbox.
Here us a link to the course on iTunes: https://itunes.apple.com/us/course/developing-ios-7-apps-for/id733644550

Related

iOS6 app state save and restoration

My app's minimum support iOS version is iOS5. And I didn't do any state save and restoration.
It works well on my self iphone4, but some users complain the app is reset when they pick up a phone call or change to other app and back.
So, I take state restoration more serious, and I want to add it into my app.
However, I have image album function, so I call ALAssetLibrary.
I need to create the exact the same thumbnail view as it was.
I have some background Operations in operationQueue, so I need to know their state and add the unfinished background operations. It's a little complicated.
Here're my questions.
1. I didn't find useful sample code, project. (session208 in WWDC2012, but they didn't release code in WWDC sample code release), Do you know any?
2. what's the best way to do it ? follow iOS6 or make it by myself?
what's the difference.
3. For ALAssetlibrary, image thumbnail viewing, how could I achieve state save and restoration?
Definitely use Apple's APIs, don't reinvent the wheel. The WWDC 2012 session about this used the WWDC 2012 app as the example to show off the feature, there was never any demo project to share to developers. However they have since (recently) released a demo to demonstrate it, you can find it here: http://developer.apple.com/library/ios/#samplecode/StateRestore/Introduction/Intro.html
It sounds like your state is complex, and I'm not sure you really want to be restoring those background operations. You probably will find it better to restore the user to a more stable part of your app.
For your ALAssetlibrary question, you would save an ID to the current image in your encodeRestorableStateWithCoder: implementation of your view controller, make sure you read up on the documentation, you'll need to conform to a protocol, set a restoration class if you're in code or using xibs (not using storyboard)... you would save the ID doing something like this:
NSString * const ImageReferenceIDKey = #"ImageReferenceID";
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
NSString *objectID = nil; // get some ID that can relocate your image
[coder encodeObject:objectID forKey:ImageReferenceIDKey];
[super encodeRestorableStateWithCoder:coder];
}
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
[super decodeRestorableStateWithCoder:coder];
NSString *objectID = [coder objectForKey:ImageReferenceIDKey];
// get into the ALAssetlibrary and use the objectID to restore which image you had.
}
Notice I call super last in the encode method, but first in the decode method.
You should be very careful about the user having changed the privacy of your access to their photos, don't crash on them, if you try to restore a photo make sure you still have permissions to do so, or you might crash.

Aspect Oriented Programming in Objective-C for iPhone

Could anyone help me first when I can use AOP, and what is it exactly in an iphone programming.
I need to access to the app project source code and call some of the functions and be notified their views loaded from outside like a library.
I found these so far, but looks very complicated to follow. Some doesnt build or the source code removed.
https://github.com/ndcube/AOP-for-Objective-C
https://github.com/moszi/AOP-in-Objective-C
ACAspect on cocoadev
If you have a specific view in a view controller and want to be notified when it is loaded, you can register for a KVO notification when that instance variable (the outlet) changes.
You'll want to read up on Key Value Observing in Cocoa. There are several methods you will need to learn how to use.
Do a search on "Introduction to Key-Value Observing Programming Guide" in the XCode docs and read that section.
Make sure you balance each call to addObserver:forKeyPath:options:context: with a call to removeObserver:forKeyPath:, or your app may crash after the observing object is deallocated.

iPhone CoreData fetch from delegate?

I've got a program which is working and uses Core Data for storage.
However, I'm not entirely sure if I should be keeping my fetch/update methods exclusively to the app delegate?
One example is for a question within the app. The question has a "left" and a "right" statement.
The delegate currently creates the new QuestionVC and passes in the questionNumber for the question. Then the QuestionVC then does a fetch to get the question object and uses the left and right properties of the object to set the text on the screen.
Should I do this the other way round...
The delegate does a fetch on the question number and then creates the QuestionVC and passes in the question object. The QuestionVC then just has to get the left and right text without having to do a fetch at all.
Any tips, advice welcome.
Thanks
Oliver
Both approaches sound valid, but if you can design your view controller hierarchy in such a way that only one object needs to know about Core Data (i.e. pass the question object to your QuestionVC) then that's probably a simpler design, which is probably better.
I personally wouldn't be doing any fetching in my app delegate, though. My app delegates only set up Core Data (i.e. the managed object context) and pass that to the root view controller. I prefer to keep my app delegates as small as possible. I don't use them as an all-purpose singleton.

Use accelerometer in a tab app

I would like to use the accelerometer in a tab app. All three tabs would access the current x,y,z and change an mage based on that data. My problem is where does the initialization of the accelerometer go so that all three tabs can update based on the data? The update only needs to happen when you are in the current tab.
I can only get this to 'work' if I initialize 3 accelerometers which is not correct. Would the data go in my appdelegate and the code to change the images in each nibs view controller?
Try to avoid putting code into appdelegate. Try using appdelegate only to handle basic stuff.
I would recomend you to implement a Singleton-Class for your Accelerometer Data.
Singletons are a very basic design pattern, that come in handy especiall in the environment of mobile devices (fewer ressources than a pc)
you can read about the singleton Pattern here: Wikipedia: Singleton Pattern
also there is a very easy way to synthesize a singelton class in your project
include the follwing file into your project syntesizesingleton.h
and within your accelerometer class put the following
#implementation yourAccelerometerClass
SYNTHESIZE_SINGLETON_FOR_CLASS(yourAccelerometerClass)
afterwards within your view controllers (or wherever) you can acces the singleton-accelerometer class by dong things similar to the following:
[[yourAccelerometerClass sharedyourAccelerometerClass] yourMethod];
hope that helps.
sam

Exchange data between two iPhone child views

Been researching how to send data from one child view to another child view. The application has several views, where one is kind of real-time Settings view. Changes in settings should effect stuff inside other views.
NSUserDefaults seems to be popular, but I don't want persistent data nor automatic saving into database/file. Looks like potential slowdown, which I want to avoid.
Second popular thing is passing a reference to some common top level object into each child view. Just haven't found any tutorial, which would show me in detail how to do this... Most likely so easy, no tutorial is needed - after you figure it out once! Would appreciate, if you can point me to right direction (URL)!
Question: I'm thinking about using one "singleton object" to store "global data", access it from everywhere anytime. What could wrong with this? If I create it at e.g. appDelegate.m it should exist before anyone tries to access it, right?
I'm looking at this sample code.
I would recommend using delegates and/or notifications.
Instead of creating a new singleton in the app delegate, add the necessary data (or, even better, references to the data) in the app delegate and have the views have references to the app delegate.
You can also set up notifications so that your views can keep track of changes to the data that they display.
The beauty of a singleton is that it is automatically created when you first access it via some [singletonClass sharedInstance]. So you don't need to "create" it while launching. If it is global data that needs to be accessed from any view singleton might be the right way of doing this.