Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 03-05-2010, 08:24 PM   #1 (permalink)
Registered Member
 
Join Date: Feb 2010
Posts: 17
yeohchan is on a distinguished road
Default NSManagedObjectContext Problem

I need some help with my managedObjectContext for this method. I am working with it but it suddenly crashed. I imported the fetcher method in the header already. Can anyone check the error.
Code:
	NSString *path=[[NSBundle mainBundle]pathForResource:@"FakeData" ofType:@"plist"];
	NSArray *array=[NSArray arrayWithContentsOfFile:path];
	fetcher = [FlickrFetcher sharedInstance];
	if([fetcher databaseExists]==YES){
		NSManagedObjectContext *entity=[NSEntityDescription insertNewObjectForEntityForName:@"PersonList" inManagedObjectContext:[fetcher managedObjectContext]];
		NSLog(@"%@ %@ %@",fetcher);
	}
Here is the header file
Code:
@interface FlickrFetcher : NSObject {
    NSManagedObjectModel *managedObjectModel;
    NSManagedObjectContext *managedObjectContext;
    NSPersistentStoreCoordinator *persistentStoreCoordinator;
}

// Returns the 'singleton' instance of this class
+ (id)sharedInstance;

// Checks to see if any database exists on disk
- (BOOL)databaseExists;

// Returns the NSManagedObjectContext for inserting and fetching objects into the store
- (NSManagedObjectContext *)managedObjectContext;

// Returns an array of objects already in the database for the given Entity Name and Predicate
- (NSArray *)fetchManagedObjectsForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate;

// Returns an NSFetchedResultsController for a given Entity Name and Predicate
- (NSFetchedResultsController *)fetchedResultsControllerForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate;

@end
Here is the implementation
Code:
#import "FlickrFetcher.h"

@interface FlickrFetcher ()

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (NSString *)applicationDocumentsDirectory;

@end

@implementation FlickrFetcher

+ (id)sharedInstance
{
	static id master = nil;
	
	@synchronized(self)
	{
		if (master == nil)
			master = [self new];
	}
    
    return master;
}


- (NSFetchedResultsController *)fetchedResultsControllerForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate {
    NSFetchedResultsController *fetchedResultsController;
    
    /*
	 Set up the fetched results controller.
     */
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:[self managedObjectContext]];
	[fetchRequest setEntity:entity];
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:20];
	
	// Edit the sort key as appropriate.
	NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
	NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
	
	[fetchRequest setSortDescriptors:sortDescriptors];
	
    // Add a predicate if we're filtering by user name
    if (predicate) {
        [fetchRequest setPredicate:predicate];
    }
    
	// Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
	fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:@"Root"];
	
	[fetchRequest release];
	[sortDescriptor release];
	[sortDescriptors release];
	
	return [fetchedResultsController autorelease];
}

- (NSArray *)fetchManagedObjectsForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate
{
	NSManagedObjectContext	*context = [self managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
	
	NSFetchRequest	*request = [[NSFetchRequest alloc] init];
	request.entity = entity;
	request.predicate = predicate;
	
	NSArray	*results = [context executeFetchRequest:request error:nil];
	[request release];
	
	return results;
}


#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 by merging all of the models found in the application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    return managedObjectModel;
}

- (NSString *)databasePath
{
	return [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"temp.sqlite"];
}

/**
 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	*path = [self databasePath];
    NSURL *storeUrl = [NSURL fileURLWithPath:path];
	
	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.
		 */
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
    }
	
    return persistentStoreCoordinator;
}

- (BOOL)databaseExists
{
	NSString	*path = [self databasePath];
	BOOL		databaseExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
	
	return databaseExists;
}


#pragma mark -
#pragma mark Application's Documents directory

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
	return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    [managedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];

    [super dealloc];
}

@end
This is the plist file in Source Code Format
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
	<dict>
		<key>path</key>
		<string>photo1.jpg</string>
		<key>name</key>
		<string>Urban disaster</string>
		<key>user</key>
		<string>Josh</string>
	</dict>
	<dict>
		<key>path</key>
		<string>photo2.jpg</string>
		<key>name</key>
		<string>Concrete pitch forks</string>
		<key>user</key>
		<string>Josh</string>
	</dict>
	<dict>
		<key>path</key>
		<string>photo3.jpg</string>
		<key>name</key>
		<string>Leaves on fire</string>
		<key>user</key>
		<string>Al</string>
	</dict>
</array>
</plist>
yeohchan is offline   Reply With Quote
Old 03-05-2010, 08:32 PM   #2 (permalink)
Registered Member
 
Join Date: Feb 2010
Posts: 17
yeohchan is on a distinguished road
Default

This is what the error appears on the console
Code:
Unresolved error Error Domain=NSCocoaErrorDomain Code=134100 UserInfo=0x3a2a8b0 "Operation could not be completed. (Cocoa error 134100.)", {
    metadata =     {
        NSPersistenceFrameworkVersion = 248;
        NSStoreModelVersionHashes =         {
            PersonList = <3a887028 d40b8996 7298fd21 ecdaf060 555a33ed bf01ceac 42ef4681 ed562d24>;
            PhotoList = <3abbb083 4d9aa84d 9d15fdd3 1aee1c07 8bd17399 9f373394 ad10ac12 664ca784>;
        };
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =         (
        );
        NSStoreType = SQLite;
        NSStoreUUID = "14F6B547-0B58-454E-B3C2-9F014BE64309";
    };
    reason = "The model used to open the store is incompatible with the one used to create the store";
}
yeohchan is offline   Reply With Quote
Old 03-05-2010, 08:47 PM   #3 (permalink)
Registered Member
 
Join Date: Feb 2010
Posts: 17
yeohchan is on a distinguished road
Default NSPredicate

I got my problem solved, but I have an error with NSPredicate
Code:
	NSString *path=[[NSBundle mainBundle]pathForResource:@"FakeData" ofType:@"plist"];
	NSArray *array=[NSArray arrayWithContentsOfFile:path];
	fetcher = [FlickrFetcher sharedInstance];
	NSManagedObjectContext *context=[fetcher managedObjectContext];
	NSManagedObjectContext *entity=[NSEntityDescription insertNewObjectForEntityForName:@"PersonList" inManagedObjectContext:context];
	NSString *string=[NSString stringWithString:@"user"];
	NSPredicate *predicate=[NSPredicate predicateWithFormat:@"array contains [cd] %@",string];
	NSArray *names=[fetcher fetchManagedObjectsForEntity:@"PersonList" withPredicate:predicate];
	if([fetcher databaseExists]==YES){
		NSLog(@"%@ %@ %@",fetcher,entity);
	}
yeohchan is offline   Reply With Quote
Old 09-11-2010, 12:34 AM   #4 (permalink)
Registered Member
 
Join Date: Sep 2010
Posts: 5
LeenaTekani is on a distinguished road
Default

if u find solution thn plz tell me i m also havin same type of error...
LeenaTekani is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 351
10 members and 341 guests
2Apps1Day, akacaj, c2matrix, esoteric, givensur, HemiMG, mjnafjke, Pudding, SLIC, Techgirl-52
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,650
Threads: 94,115
Posts: 402,887
Top Poster: BrianSlick (7,990)
Welcome to our newest member, soohyun
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 10:11 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0