I have a cartArray(in AppDelegate.h #interface above) that need to be saved when the app in background mode or the app closed. The app worked fine when the cartArray has nothing but crashed when I added an item (Cart) in it and entered the background or closed the application by pressing the minus sign. My cartArray contains cart class in it.
May I know what is happening? The tutorial online is so complicated and I always find myself lost in the middle of explanation.
[AppDelegate.m]
- (void)applicationDidEnterBackground:(UIApplication *)application {
[AppDelegate saveData];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
[AppDelegate getData];
}
+(NSString *) getPathToAchieve{ NSLog(#"+++++getPathToAchieve");
static NSString* docsDir = nil;
if (docsDir == nil) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [paths objectAtIndex:0];
}
NSString *fullFileName = [NSString stringWithFormat:#"%#.plist", docsDir];
return fullFileName;
}
- (void)applicationWillTerminate:(NSNotification *)notification{
[cartArray writeToFile:[AppDelegate getPathToAchieve] atomically:YES];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{ self = [super init];
if (self != nil)
{
cartArray = [aDecoder decodeObjectForKey:#"cartArrayKeys"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)anEncoder
{
[anEncoder encodeObject:cartArray forKey:#"cartArrayKeys"];
}
+(void)saveData{
[NSKeyedArchiver archiveRootObject:cartArray toFile:[self getPathToAchieve] ];
}
+(id)getData{
return [NSKeyedUnarchiver unarchiveObjectWithFile:[self getPathToAchieve]];
}
Your code is pretty messy. First, implement -(id)initWithCoder: and -(void)encodeWithCoder: in your Cart class, not AppDelegate class (and make sure Cart conforms to NSCoding protocol):
- (void) encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.title forKey:#"title"];
[encoder encodeObject:self.description forKey:#"description"];
.....
}
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
self.title = [decoder decodeObjectForKey:#"title"] ;
self.description = [decoder decodeObjectForKey:#"description"] ;
....
}
return self;
}
Second, implement -(void)saveData and -(void)getData:
-(void)saveData{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:cartArray] forKey:#"cartArray"];
}
-(void)getData{
NSData *savedArray = [[NSUserDefaults standardUserDefaults] objectForKey:#"cartArray"];
if (savedArray != nil)
{
NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:savedArray];
if (oldArray != nil) {
cartArray = [[NSMutableArray alloc] initWithArray:oldArray];
} else {
cartArray = [[NSMutableArray alloc] init];
}
}
}
Call saveData when application is going to be terminated / entered background.
Call getData when application has loaded.
do all your saving in
- (void)applicationWillResignActive:(UIApplication *)application
from the documentation:
Tells the delegate that the application is about to become inactive.
This method is called to let your application know that it is about to
move from the active to inactive state. This can occur for certain
types of temporary interruptions (such as an incoming phone call or
SMS message) or when the user quits the application and it begins the
transition to the background state. An application in the inactive
state continues to run but does not dispatch incoming events to
responders. You should use this method to pause ongoing tasks, disable
timers, and throttle down OpenGL ES frame rates. Games should use this
method to pause the game. An application in the inactive state should
do minimal work while it waits to transition to either the active or
background state.
Array is a temporary storage if you want to save some data in permanent then try to use NSUSerDefult. After closing app array may vanish. NSUSerDefult data not vanish. NSUserDefault vanish only when app delete or Remove app from simulator.
Related
Hi i am using iCloud support for my application and using UIDocument for storage. I was able to save data to iCloud and fetch the same for first time. But when i deleted and reinstalled the app on device, the seems to crash with EXC BAD ACCESS while trying to unarchive data using NSKeyUnarchiver.
Code.
BuyerDocument.m // UIDocument Subclass
// Accessor for BuyerData
- (BuyerData *)data {
if (_data == nil) {
if (self.fileWrapper != nil) {
self.data = [self decodeObjectFromWrapperWithPreferredFilename:BUYER_FILENAME]; // BUYER_FILENAME = #"buyer.data"
} else {
self.data = [[BuyerData alloc] init];
}
}
return _data;
}
- (id)decodeObjectFromWrapperWithPreferredFilename:(NSString *)preferredFilename {
NSFileWrapper * fileWrapper = [self.fileWrapper.fileWrappers objectForKey:preferredFilename];
if (!fileWrapper) {
NSLog(#"Unexpected error: Couldn't find %# in file wrapper!", preferredFilename);
return nil;
}
if([fileWrapper isRegularFile]){
NSLog(#"is regular wrapper");
}
NSData * data = [fileWrapper regularFileContents];
NSLog(#"data %#",data); // This logs successfully
// NSLog(#"data bytes %#",[data bytes]) // This also causes app to crash.
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; // App will crash here
return [unarchiver decodeObjectForKey:#"data"];
}
Loading BuyerDocument here.
- (void)loadDocAtURL:(NSURL *)fileURL {
// Open doc so we can read metadata
BuyerDocument * doc = [[BuyerDocument alloc] initWithFileURL:fileURL];
[doc openWithCompletionHandler:^(BOOL success) {
.......
BuyerData * data = doc.data;
....
[doc closeWithCompletionHandler:^(BOOL success) {
.....
}];
}
BuyerData.m
#define kVersionKey #"Version"
#define kNameKey #"Name"
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeInt:1 forKey:kVersionKey];
[encoder encodeObject:self.name forKey:kNameKey];
}
- (id)initWithCoder:(NSCoder *)decoder {
[decoder decodeIntForKey:kVersionKey];
NSString *nameData = [decoder decodeObjectForKey:kNameKey];
// NSLog(#">>>>>>>>>>>>>>>>>>> %#",name); // This logs for first 2-3 files and then crash occurs
return [self initWithName:nameData];
}
As i said when i first added data everything ran fine, it was only after deleting and reinstalling that crash began to occur. Also first 3-4 names are fetched and displayed in tableview before this crash occurs.
Tried this but of no help
I am fairly new to UIDocument and NSCoding. So can't say much about them. But i guess some how the issue might be with linked to NSData getting lost or corrupted out there. Am i missing something basic and important here. What am i doing wrong?
I am developing an iOS app that has a button with a microphone on it (along with other features). When the user presses the microphone, it gets highlighted and the app should now start recording sound from the deviceĀ“s microphone and send to a server (a server dedicated to the app, developed by people that I know, so I can affect its design).
I am looking for the simplest yet sturdiest approach to do this, i.e. I have no need to develop a complicated streaming solution or VoIP functionality, unless it is as simple to do as anything else.
The main problem is that we have no idea for how long the user will be recording sound, but we want to make sure that sounds are sent to the server continuously, we do not wish to wait until the user has finished recording. It is okay if the data arrives to the server in chunks however we do not wish to miss any information that the user may be recording, so one chunk must continue where the previous one ended and so on.
Our first thought was to create "chunks" of sound clips of for example 10 seconds and send them continuously to the server. Is there any streaming solution that is better/simpler that I am missing out on?
My question is, what would be the most simple but still reliable approach on solving this task on iOS?
Is there a way to extract chunks of sound from a running recording by AVAudioRecorder, without actually stopping the recording?
look at this
in this tutorial, the sound recorded will be saved at soundFileURL, then you will just have to create an nsdata with that content, and then send it to your server.
hope this helped.
EDIT :
I just created a version that contain 3 buttons, REC, SEND and Stop :
REC : will start recording into a file.
SEND : will save what was recorded on that file in a NSData, and send it to a server, then will restart recording.
and STOP : will stop recording.
here is the code :
in your .h file :
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController <AVAudioRecorderDelegate>
#property (nonatomic, retain) AVAudioRecorder *audioRecorder;
#property (nonatomic, retain) IBOutlet UIButton *recordButton;
#property (nonatomic, retain) IBOutlet UIButton *stopButton;
#property (nonatomic, retain) IBOutlet UIButton *sendButton;
#property BOOL stoped;
- (IBAction)startRec:(id)sender;
- (IBAction)sendToServer:(id)sender;
- (IBAction)stop:(id)sender;
#end
and in the .m file :
#import "ViewController.h"
#implementation ViewController
#synthesize audioRecorder;
#synthesize recordButton,sendButton,stopButton;
#synthesize stoped;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
sendButton.enabled = NO;
stopButton.enabled = NO;
stoped = YES;
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:#"tempsound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
audioRecorder.delegate = self;
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[audioRecorder prepareToRecord];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (BOOL) sendAudioToServer :(NSData *)data {
NSData *d = [NSData dataWithData:data];
//now you'll just have to send that NSData to your server
return YES;
}
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
NSLog(#"stoped");
if (!stoped) {
NSData *data = [NSData dataWithContentsOfURL:recorder.url];
[self sendAudioToServer:data];
[recorder record];
NSLog(#"stoped sent and restarted");
}
}
- (IBAction)startRec:(id)sender {
if (!audioRecorder.recording)
{
sendButton.enabled = YES;
stopButton.enabled = YES;
[audioRecorder record];
}
}
- (IBAction)sendToServer:(id)sender {
stoped = NO;
[audioRecorder stop];
}
- (IBAction)stop:(id)sender {
stopButton.enabled = NO;
sendButton.enabled = NO;
recordButton.enabled = YES;
stoped = YES;
if (audioRecorder.recording)
{
[audioRecorder stop];
}
}
#end
Good Luck.
It might actually be easier to have fixed-size chunks, instead of fixed-time. Then you can have two buffers, one that you currently fill with sample data. When the active buffer is full, then switch to fill the other buffer, while sending a signal to a sender-thread that takes the first buffer and sends it to the server.
You can of course use fixed-time instead, but then you need to make sure that the buffer is large enough to keep all samples, or use a dynamic buffer that can increase in size when needed. The double-buffering and sending thread can still be the same though.
In my app, i have Used UiimagepickerController for taking Video.in bettween my programm received any web service Which belongs to my app,
i have to stop Video Capture and save video.
i have Used StopVideoCapture to do above thing ,but it doesn't call delegate - `
(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
How to force call above delegate ??.or How to handle interruption Handling inUIImagePickerController`.. any idea?
The idea with delegate methods is not that you call those methods - "They call you".
So I would not consider calling the delegate method yourself a good practise. However, if you present the UIImagePickerViewController with a modal dialogue (which I guess is common for such a picker) then you can close it like this outside of your delegate method:
[[yourPicker parentViewController] dismissModalViewControllerAnimated:YES];
Source
Update: You can use the ALAssetsLibrary for accessing the stored data in your iPhone media library. I recently had to do a similar project where I had to list all images on the iPhone. The Github project ELCImagePickerController.git was very useful since it shows how the items in your library can be accessed. So you'll do something like this:
#import <AssetsLibrary/AssetsLibrary.h>
// ....
-(void)fetchPhotoAlbums{
if(!self.assetsGroups){
self.assetsGroups = [NSMutableDictionary dictionary];
}
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
#autoreleasepool {
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop){
if (group == nil){
// Completed
[self.delegate pictureService:self fetchedAlbums:returnArray];
return;
}
Album *currentAlbum = [self albumForAssetsGroup:group];
// Store the Group for later retrieving the pictures for the album
[self.assetsGroups setObject:group forKey:currentAlbum.identifier];
[returnArray addObject:currentAlbum];
[self.delegate pictureService:self fetchedAlbums:returnArray];
};
void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
NSLog(#"A problem occured %#", [error description]);
};
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:assetGroupEnumberatorFailure];
}
}
-(void)fetchPhotosForAlbum:(Album *)album{
ALAssetsGroup *currentGroup = [self.assetsGroups objectForKey:album.identifier];
NSMutableArray *photos = [NSMutableArray array];
[currentGroup enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop){
if(asset == nil){
[self.delegate pictureService:self fetchedPictures:photos forAlbum:album];
return;
}
[photos addObject:[self pictureForAsset:asset]];
}];
}
Additionally I use two mapper methods to convert the AL-classes into my own model classes.
- (Album *)albumForAssetsGroup:(ALAssetsGroup *)assetsGroup{
Album *album = [[Album alloc] init];
album.title = [assetsGroup valueForProperty:ALAssetsGroupPropertyName];
album.identifier = [assetsGroup valueForProperty: ALAssetsGroupPropertyPersistentID];
album.assetsCount = assetsGroup.numberOfAssets;
album.thumbnail = [UIImage imageWithCGImage:assetsGroup.posterImage];
return album;
}
- (Picture *)pictureForAsset:(ALAsset *)asset{
Picture *picture = [[Picture alloc]init];
picture.identifier = [((NSArray *)[asset valueForProperty: ALAssetPropertyRepresentations]) objectAtIndex:0];
picture.thumbnail = [UIImage imageWithCGImage:asset.thumbnail];
return picture;
}
See the AssetsLibrary Documentation
I'm new. Been trying to save/load a couple of arrays but to no avail.
I have "Global.h" and "Global.m" providing arrays for other classes.
in Global.h
extern NSMutableArray *arrayTable;
extern NSMutableArray *arrayPurpose;
#interface Global : NSObject <NSCoding> {
}
in Global.m
NSMutable *arrayTable;
MSMutable *arrayPurpose;
I have other views/controllers/classes/whatever that work with these arrays and they are functioning. What do I put inside this "Global" and the "AppDelegate.h" and "AppDelegate.m" so that these arrays are saved when this app goes into background and loads when the app starts? I need to use this "NSDocumentDirectory" because this data is important.
Please keep your explanations REALLLLLLY EASY. I have less than a week's experience. Thanks!!
Edit: Did what Joris suggested.
Added this to the AppDelegate
-(NSString *)archivePath {
NSString *docDir =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)objectAtIndex: 0];
return [docDir stringByAppendingPathComponent:#"TableData.dat"];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[NSKeyedArchiver archiveRootObject:arrayTable toFile:self.archivePath];
[NSKeyedArchiver archiveRootObject:arrayPurpose toFile:self.archivePath];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[window addSubview:rootController.view];
[self.window makeKeyAndVisible];
arrayTable = [NSKeyedUnarchiver unarchiveObjectWithFile:[self archivePath]];
arrayPurpose = [NSKeyedUnarchiver unarchiveObjectWithFile:[self archivePath]];
if (arrayTable == nil) {
arrayPurpose = [[NSMutableArray alloc]init];
arrayTable = [[NSMutableArray alloc]init];
}
return YES;
}
Not very detailed but:
in the suspend method of your appdelegate you can use:
[NSKeyedArchiver archiveRootObject:arrayTable toFile:...];
and in the resume method:
arrayTable = [[NSKeyedUnarchiver unarchiveObjectWithFile:...] retain];
I can't figure out how come the row count is correct but the uitableview won't load the row contents the NSLog shows carresults=(null), but the row count is correct, on the simulator if I relaunch, the carresults get filled. It seems like I'm missing my first fetchedResultsController teh first time through, but how can it get the row count if it doesn't know what' there?
Help!! any Ideas? Thanks, Mike
The titleForHeaderInSection works fine, brings back the correct titles:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[[fetchedResultsController1 sections] objectAtIndex:section] name];
}
This brings back the correct row count:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController1 sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
This does not populate the cells until a rebuild on simulator, never populates the iPhone.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *FirstViewIdentifier = #"FirstViewIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FirstViewIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = firstviewCell;
self.firstviewCell = nil;
}
Cars *carresults = (Cars *)[fetchedResultsController1 objectAtIndexPath:indexPath];
NSLog(#"carresults %#", carresults.make);
EDIT: Here is the FRC:
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[[[UIApplication sharedApplication] delegate] managedObjectContext] sectionNameKeyPath:#"key" cacheName:#"Root1"];
self.fetchedResultsController = aFetchedResultsController;
fetchedResultsController.delegate = self;
Since you haven't provided any debug info I can only guess as to what's wrong, so I'll ask you some questions. Does it in fact instantiate the firstviewCell property with the nib. If the cell is not connected to the firstviewCell property of the File Owner (in the nib) it won't work. Otherwise if the fetchedResultsController doesn't have anything in it you'll get an error if you try to access the data. If the nslog fires then you probably didn't get an error, which means that your Cars objects are being fetched theres just nothing in them. to see whats in the fetchedResultsController call NSLog(#"Fetched Objects: %#",[[fetchedResultsController fetchedObjects] description]); Keep in mind though, that fetchedObjects is only updated when you call performFetch. Since you say carresults gets filled when you restart the app it may be possible that you need to call saveContext for the results to get loaded. The only reason for this is if you create the data at runtime, before the table view gets loaded. Otherwise I would assume you have the table view set as the fetched results controller's delegate so that it gets informed of any changes and responds appropriately. The app delegate usually does this on applicationWillResign active or applicationWillTerminate (applicationWillTerminate doesn't seem to get called by iOS4 during normal closing).The only other thing I could think of is that maybe your SectionInfo object might contain the wrong information, try debugging that too.
Good Luck,
Rich
Edit: I appologize, the save context method is a method added to your appdelegate when you create an app based on core data. a good way to make a core data stack is to wrap it in an NSObject, it can be useful to make it a singleton ,unless of course you need concurrency in which case it gets really complicated. This is the implementation including the save context function:
// CoreDataStack.h
// do not call alloc, retain, release, copy or especially copyWithZone: (because I didn't bother to override it since you shouldn't try to create this in anything but the main thread, and definatly don't dispatchasync this object's methods)
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#define kYourAppName #"This should be replaced by the name of your datamodel"
#interface CoreDataStack : NSObject {
#private
NSManagedObjectContext *managedObjectContext_;
NSManagedObjectModel *managedObjectModel_;
NSPersistentStoreCoordinator *persistentStoreCoordinator_;
}
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
+ (CoreDataStack *)sharedManager;
+ (void)sharedManagerDestroy;
// call this in your app delegate in applicationWillTerminate and applicationWillResignActive
- (void)saveContext;
- (NSURL *)applicationLibraryDirectory;
#end
// CoreDataStack.m
#import "CoreDataStack.h"
#interface CoreDataStack ()
- (oneway void)priv_release;
#end
#implementation CoreDataStack
static CoreDataStack *sharedManager = nil;
+ (CoreDataStack *)sharedManager {
if (sharedManager != nil) {
return sharedManager;
}
sharedManager = [[CoreDataStack alloc] init];
return sharedManager;
}
+ (void)sharedManagerDestroy {
if (sharedManager) {
[sharedManager priv_release];
sharedManager = nil;
}
}
- (id)retain {
return self;
}
- (id)copy {return self;}
- (oneway void)release{}
- (oneway void)priv_release {
[super release];
}
- (void)saveContext {
NSError *error = nil;
if (managedObjectContext_ != nil) {
if ([managedObjectContext_ hasChanges] && ![managedObjectContext_ save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
//abort();
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"The app has run into an error trying to save, please exit the App and contact the developers. Exit the program by double-clicking the home button, then tap and hold the iMean icon in the task manager until the icons wiggle, then tap iMean again to terminate it"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
#pragma mark -
#pragma mark Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext_ != nil) {
return managedObjectContext_;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext_ = [[NSManagedObjectContext alloc] init];
[managedObjectContext_ setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext_;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel_ != nil) {
return managedObjectModel_;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"kYourAppName" withExtension:#"momd"];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel_;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSString *yourAppName = [[NSString stringWithFormat:#"%#.sqlite",kYourAppName] autorelease];
NSURL *storeURL = [[self applicationLibraryDirectory] URLByAppendingPathComponent:yourAppName];
NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
// abort();
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"The app has run into an error trying to load it's data model, please exit the App and contact the developers. Exit the program by double-clicking the home button, then tap and hold the iMean icon in the task manager until the icons wiggle, then tap iMean again to terminate it"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
return persistentStoreCoordinator_;
}
#pragma mark -
#pragma mark Application's Library directory
/**
Returns the URL to the application's Documents directory.
*/
// returns the url of the application's Library directory.
- (NSURL *)applicationLibraryDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc {
// release and set all pointers to nil to avoid static issues
[managedObjectContext_ release];
managedObjectContext_ = nil;
[managedObjectModel_ release];
managedObjectModel_ = nil;
[persistentStoreCoordinator_ release];
persistentStoreCoordinator_ = nil;
[super dealloc];
}
#end