Search Results

Search found 106 results on 5 pages for 'nsfetchrequest'.

Page 4/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • NSFetchedResultsController crashing on performFetch: when using a cache

    - by Oliver
    I make use of NSFetchedResultsController to display a bunch of objects, which are sectioned using dates. On a fresh install, it all works perfectly and the objects are displayed in the table view. However, it seems that when the app is relaunched I get a crash. I specify a cache when initialising the NSFetchedResultsController, and when I don't it works perfectly. Here is how I create my NSFetchedResultsController: - (NSFetchedResultsController *)results { // If we are not nil, stop here if (results != nil) return results; // Create the fetch request, entity and sort descriptors NSFetchRequest *fetch = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext]; NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"utc_start" ascending:YES]; NSArray *descriptors = [[NSArray alloc] initWithObjects:descriptor, nil]; // Set properties on the fetch [fetch setEntity:entity]; [fetch setSortDescriptors:descriptors]; // Create a fresh fetched results controller NSFetchedResultsController *fetched = [[NSFetchedResultsController alloc] initWithFetchRequest:fetch managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"day" cacheName:@"Events"]; fetched.delegate = self; self.results = fetched; // Release objects and return our controller [fetched release]; [fetch release]; [descriptor release]; [descriptors release]; return results; } These are the messages I get when the app crashes: FATAL ERROR: The persistent cache of section information does not match the current configuration. You have illegally mutated the NSFetchedResultsController's fetch request, its predicate, or its sort descriptor without either disabling caching or using +deleteCacheWithName: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FATAL ERROR: The persistent cache of section information does not match the current configuration. You have illegally mutated the NSFetchedResultsController's fetch request, its predicate, or its sort descriptor without either disabling caching or using +deleteCacheWithName:' I really have no clue as to why it's saying that, as I don't believe I'm doing anything special that would cause this. The only potential issue is the section header (day), which I construct like this when creating a new object: // Set the new format [formatter setDateFormat:@"dd MMMM"]; // Set the day of the event [event setValue:[formatter stringFromDate:[event valueForKey:@"utc_start"]] forKey:@"day"]; Like I mentioned, all of this works fine if there is no cache involved. Any help appreciated!

    Read the article

  • How to convert an NSArray of NSManagedObjects to NSData

    - by carok
    Hi, I'm new to Objective C and was wondering if anyone can help me. I am using core data with a sqlite database to hold simple profile objects which have a name and a score attribute (both of which are of type NSString). What I want to do is fetch the profiles and store them in an NSData object, please see my code below: NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"GamerProfile" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES]; NSArray *sortDecriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDecriptors]; [sortDescriptor release]; [sortDecriptors release]; NSError *error; NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:items]; [self SendData:data]; [fetchRequest release]; When I run the code I'm getting the error "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[GamerProfile encodeWithCoder:]: unrecognized selector sent to instance 0x3f4b530'" I presume I have to add an encodeWithCoderClass to my core data NSManagedObject object (GamerProfile) but I'm not sure how to do this even after reading the documentation, My attempt at doing this is below. I'm not sure if I'm going along the right lines with this as get a warning stating "NSManagedObject" may not respond to '-encodeWithCoder'" I would really, really appreciate it if someone could point me in the right direction!! Thanks C Here is the code for my GamerProfile (CoreData NSManagedObject Object) with my attempt at adding an encodeWithCoder method... Header File #import <CoreData/CoreData.h> @interface GamerProfile : NSManagedObject <NSCoding> { } @property (nonatomic, retain) NSString * GamerScore; @property (nonatomic, retain) NSString * Name; - (void)encodeWithCoder:(NSCoder *)coder; @end Code File #import "GamerProfile.h" @implementation GamerProfile @dynamic GamerScore; @dynamic Name; - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeObject:GamerScore forKey:@"GamerScore"]; [coder encodeObject:Name forKey:@"Name"]; }

    Read the article

  • Passing a ManagedObjectContext to a second view

    - by amo
    I'm writing my first iPhone/Cocoa app. It has two table views inside a navigation view. When you touch a row in the first table view, you are taken to the second table view. I would like the second view to display records from the CoreData entities related to the row you touched in the first view. I have the CoreData data showing up fine in the first table view. You can touch a row and go to the second table view. I'm able to pass info from the selected object from the first to the second view. But I cannot get the second view to do its own CoreData fetching. For the life of me I cannot get the managedObjectContext object to pass to the second view controller. I don't want to do the lookups in the first view and pass a dictionary because I want to be able to use a search field to refine results in the second view, as well as insert new entries to the CoreData data from there. Here's the function that transitions from the first to the second view. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here -- for example, create and push another view controller. NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath]; SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil]; secondViewController.tName = [[selectedObject valueForKey:@"name"] description]; secondViewController.managedObjectContext = [self managedObjectContext]; [self.navigationController pushViewController:secondViewController animated:YES]; [secondViewController release]; } And this is the function inside SecondViewController that crashes: - (void)viewDidLoad { [super viewDidLoad]; self.title = tName; NSError *error; if (![[self fetchedResultsController] performFetch:&error]) { // <-- crashes here // Handle the error... } } - (NSFetchedResultsController *)fetchedResultsController { if (fetchedResultsController != nil) { return 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. // **** crashes on the next line because managedObjectContext == 0x0 NSEntityDescription *entity = [NSEntityDescription entityForName:@"SecondEntity" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // <snip> ... more code here from Apple template, never gets executed because of the crashing return fetchedResultsController; } Any ideas on what I am doing wrong here? managedObjectContext is a retained property. UPDATE: I inserted a NSLog([[managedObjectContext registeredObjects] description]); in viewDidLoad and it appears managedObjectContext is being passed just fine. Still crashing, though. Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'SecondEntity''

    Read the article

  • Adding unique objects to Core Data

    - by absolut
    I'm working on an iPhone app that gets a number of objects from a database. I'd like to store these using Core Data, but I'm having problems with my relationships. A Detail contains any number of POIs (points of interest). When I fetch a set of POI's from the server, they contain a detail ID. In order to associate the POI with the Detail (by ID), my process is as follows: Query the ManagedObjectContext for the detailID. If that detail exists, add the poi to it. If it doesn't, create the detail (it has other properties that will be populated lazily). The problem with this is performance. Performing constant queries to Core Data is slow, to the point where adding a list of 150 POI's takes a minute thanks to the multiple relationships involved. In my old model, before Core Data (various NSDictionary cache objects) this process was super fast (look up a key in a dictionary, then create it if it doesn't exist) I have more relationships than just this one, but pretty much every one has to do this check (some are many to many, and they have a real problem). Does anyone have any suggestions for how I can help this? I could perform fewer queries (by searching for a number of different ID's), but I'm not sure how much this will help. Some code: POI *poi = [NSEntityDescription insertNewObjectForEntityForName:@"POI" inManagedObjectContext:[(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext]]; poi.POIid = [attributeDict objectForKey:kAttributeID]; poi.detailId = [attributeDict objectForKey:kAttributeDetailID]; Detail *detail = [self findDetailForID:poi.POIid]; if(detail == nil) { detail = [NSEntityDescription insertNewObjectForEntityForName:@"Detail" inManagedObjectContext:[(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext]]; detail.title = poi.POIid; detail.subtitle = @""; detail.detailType = [attributeDict objectForKey:kAttributeType]; } -(Detail*)findDetailForID:(NSString*)detailID { NSManagedObjectContext *moc = [[UIApplication sharedApplication].delegate managedObjectContext]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Detail" inManagedObjectContext:moc]; NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; [request setEntity:entityDescription]; NSPredicate *predicate = [NSPredicate predicateWithFormat: @"detailid == %@", detailID]; [request setPredicate:predicate]; NSLog(@"%@", [predicate description]); NSError *error; NSArray *array = [moc executeFetchRequest:request error:&error]; if (array == nil || [array count] != 1) { // Deal with error... return nil; } return [array objectAtIndex:0]; }

    Read the article

  • iPhone: Speeding up a search that's polling 17,000 Core Data objects

    - by randombits
    I have a class that conforms to UISearchDisplayDelegate and contains a UISearchBar. This view is responsible for allowing the user to poll a store of about 17,000 objects that are currently managed by Core Data. Everytime the user types in a character, I created an instance of a SearchOperation (subclasses NSOperation) that queries Core Data to find results that might match the search. The code in the search controller looks something like: - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { // Update the filtered array based on the search text and scope in a secondary thread if ([searchText length] < 3) { [filteredList removeAllObjects]; // First clear the filtered array. [self setFilteredList:NULL]; [self.tableView reloadData]; return; } NSDictionary *searchdict = [NSDictionary dictionaryWithObjectsAndKeys:scope, @"scope", searchText, @"searchText", nil]; [aSearchQueue cancelAllOperations]; SearchOperation *searchOp = [[SearchOperation alloc] initWithDelegate:self dataDict:searchdict]; [aSearchQueue addOperation:searchOp]; } And my search is rather straight forward. SearchOperation is a subclass of NSOperation. I overwrote the main method with the following code: - (void)main { if ([self isCancelled]) { return; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:entity]; NSPredicate *predicate = NULL; predicate = [NSPredicate predicateWithFormat:@"(someattr contains[cd] %@)", searchText]; [fetchRequest setPredicate:predicate]; NSError *error = NULL; NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; [fetchRequest release]; if (self.delegate != nil) [self.delegate didFinishSearching:fetchResults]; [pool drain]; } This code works, but it has several issues. It's slow. Even though I have the search happening in a separate thread other than the UI thread, querying 17,000 objects is clearly not optimal. If I'm not careful, crashes can happen. I set the max concurrent searches in my NSOperationQueue to 1 to avoid this. What else can I do to make this search faster? I think preloading all 17,000 objects into memory might be risky. There has to be a smarter way to conduct this search to give results back to the user faster.

    Read the article

  • How to do an fetch request with expressions like this on the iPhone?

    - by dontWatchMyProfile
    The documentation has an example on how to retrieve simple values only, rather than managed objects. This remembers a lot SQL using aliases and functions to only retrieve calculated values. So, actually pretty geeky stuff. To get the minimum date from a bunch of records, this is used on the mac: NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context]; [request setEntity:entity]; // Specify that the request should return dictionaries. [request setResultType:NSDictionaryResultType]; // Create an expression for the key path. NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"creationDate"]; // Create an expression to represent the minimum value at the key path 'creationDate' NSExpression *minExpression = [NSExpression expressionForFunction:@"min:" arguments:[NSArray arrayWithObject:keyPathExpression]]; // Create an expression description using the minExpression and returning a date. NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init]; // The name is the key that will be used in the dictionary for the return value. [expressionDescription setName:@"minDate"]; [expressionDescription setExpression:minExpression]; [expressionDescription setExpressionResultType:NSDateAttributeType]; // Set the request's properties to fetch just the property represented by the expressions. [request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]]; // Execute the fetch. NSError *error; NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error]; if (objects == nil) { // Handle the error. } else { if ([objects count] > 0) { NSLog(@"Minimum date: %@", [[objects objectAtIndex:0] valueForKey:@"minDate"]; } } [expressionDescription release]; [request release]; Nice, I though - but having a deep look into NSExpression -expressionForFunction:arguments: it turns out that iPhone OS does NOT support the min: function. Well, probably there's a nifty way to use an own function for this kind of stuff on the iPhone as well? Because on thing I'm already worrying about is, how I'm gonna sort a table based on the calculated distance of targets on a map (location-based stuff).

    Read the article

  • NSSortDescriptor for NSFetchRequestController causes crash when value of sorted attribute is changed

    - by AJ
    I have an Core Data Entity with a number of attributes, which include amount(float), categoryTotal(float) and category(string) The initial ViewController uses a FethchedResultsController to retrieve the entities, and sorts them based on the category and then the categoryTotal. No problems so far. NSManagedObjectContext *moc = [self managedObjectContext]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Transaction" inManagedObjectContext:moc]; NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; [request setEntity:entityDescription]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(dateStamp >= %@) AND (dateStamp =< %@)", startDate, endDate]; [request setPredicate:predicate]; NSSortDescriptor *sortByCategory = [[NSSortDescriptor alloc] initWithKey:@"category" ascending:sortOrder]; NSSortDescriptor *sortByTotals = [[NSSortDescriptor alloc] initWithKey:@"categoryTotal" ascending:sortOrder]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortByTotals, sortByCategory, nil]; [request setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:managedObjectContext sectionNameKeyPath:@"category" cacheName:nil]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; On selecting a row (tableView:didSelectRowAtIndexPath), another view controller is loaded that allows editing of the amount field for the selected entity. Before returning to the first view, categoryTotal is updated by the new ‘amount’. The problem comes when returning to the first view controller, the app bombs with *Serious application error. Exception was caught during Core Data change processing: Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted). with userInfo (null) Program received signal: “EXC_BAD_ACCESS”.* This seems to be courtesy of NSSortDescriptor *sortByTotals = [[NSSortDescriptor alloc] initWithKey:@"categoryTotal" ascending:sortOrder]; If I remove this everything works as expected, but obviously without the sorting I want. I'm guessing this is to do with the sorting order changing due to categoryTotal changing (deletion / insertion) but can't find away fix this. I've verified that values are being modified correctly in the second view, so it appears down to the fetchedResultsController being confused. If the categoryAmount is changed to one that does not change the sort order, then no error is generated I'm not physically changing (ie deleting) the number of items the fetchedResultsController is returning ... the only other issue I can find that seem to generate this error Any ideas would be most welcome Thanks, AJ

    Read the article

  • Updating UISearchDisplayController with Core Data results using GCD

    - by Brian Halpin
    I'm having trouble displaying the results from Core Data in my UISearchDisplayController when I implement GCD. Without it, it works, but obviously blocks the UI. In my SearchTableViewController I have the following two methods: - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { // Tell the table data source to reload when text changes [self filterContentForSearchText:searchString]; // Return YES to cause the search result table view to be reloaded. return YES; } // Update the filtered array based on the search text -(void)filterContentForSearchText:(NSString*)searchText { // Remove all objects from the filtered search array [self.filteredLocationsArray removeAllObjects]; NSPredicate *predicate = [CoreDataMaster predicateForLocationUsingSearchText:@"Limerick"]; CoreDataMaster *coreDataMaster = [[CoreDataMaster alloc] init]; // Filter the array using NSPredicate self.filteredLocationsArray = [NSMutableArray arrayWithArray: [coreDataMaster fetchResultsFromCoreDataEntity:@"City" UsingPredicate:predicate]]; } You can probably guess that my problem is with returning the array from [coreDataMaster fetchResultsFromCoreDataEntity]. Below is the method: - (NSArray *)fetchResultsFromCoreDataEntity:(NSString *)entity UsingPredicate:(NSPredicate *)predicate { NSMutableArray *fetchedResults = [[NSMutableArray alloc] init]; dispatch_queue_t coreDataQueue = dispatch_queue_create("com.coredata.queue", DISPATCH_QUEUE_SERIAL); dispatch_async(coreDataQueue, ^{ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entity inManagedObjectContext:self.managedObjectContext]; NSSortDescriptor *nameSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObjects:nameSort, nil]; [fetchRequest setEntity:entityDescription]; [fetchRequest setSortDescriptors:sortDescriptors]; // Check if predicate is set if (predicate) { [fetchRequest setPredicate:predicate]; } NSError *error = nil; NSArray *fetchedManagedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; for (City *city in fetchedManagedObjects) { [fetchedResults addObject:city]; } NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSArray arrayWithArray:fetchedResults] forKey:@"results"]; [[NSNotificationCenter defaultCenter] postNotificationName:@"fetchResultsComplete" object:nil userInfo:userInfo]; }); return [NSArray arrayWithArray:fetchedResults]; } So the thread hasn't finished executing by the time it returns the results to self.filteredLocationsArray. I've tried added a NSNotification which passes the NSDictionary to this method: - (void)updateSearchResults:(NSNotification *)notification { NSDictionary *userInfo = notification.userInfo; NSArray *array = [userInfo objectForKey:@"results"]; self.filteredLocationsArray = [NSMutableArray arrayWithArray:array]; [self.tableView reloadData]; } I've also tried refreshing the searchViewController like [self.searchDisplayController.searchResultsTableView reloadData]; but to no avail. I'd really appreciate it if someone could point me in the right direction and show me where I might be going wrong. Thanks

    Read the article

  • EXC_MEMORY_ACCESS when trying to delete from Core Data ($cash solution)

    - by llloydxmas
    I have an application that downloads an xml file, parses the file, and creates core data objects while doing so. In the parse code I have a function called 'emptydatacontext' that removes all items from Core Data before creating replacements items from the xml data. This method looks like this: -(void) emptyDataContext { NSFetchRequest * allCon = [[NSFetchRequest alloc] init]; [allCon setEntity:[NSEntityDescription entityForName:@"Condition" inManagedObjectContext:managedObjectContext]]; NSError * error = nil; NSArray * conditions = [managedObjectContext executeFetchRequest:allCon error:&error]; DebugLog(@"ERROR: %@",error); DebugLog(@"RETRIEVED: %@", conditions); [allCon release]; for (NSManagedObject * condition in conditions) { [managedObjectContext deleteObject:condition]; } // Update the data model effectivly removing the objects we removed above. //NSError *error; if (![managedObjectContext save:&error]) { DebugLog(@"%@", [error domain]); } } The first time this runs it deletes all objects and functions as it should - creating new objects from the xml file. I created a 'update' button that starts the exact same process of retrieving the file the proceeding with the parse & build. All is well until its time to delete the core data objects. This 'deleteObject' call creates a "EXC_BAD_ACCESS" error each time. This only happens on the second time through. Captured errors return null. If I log the 'conditions' array I get a list of NSManagedObjects on the first run. On the second this log request causes a crash exactly as the deleteObject call does. I have a feeling it is something very simple I'm missing or not doing correctly to cause this behavior. The data works great on my tableviews - its only when trying to update I get the crashes. I have spent days & days on this trying numerous alternative methods. Whats left of my hair is falling out. I'd be willing to ante up some cash for anyone willing to look at my code and see what I'm doing wrong. Just need to get past this hurdle. Thanks in advance for the help!

    Read the article

  • How to assign a value to an pointer-pointer passed in call by reference?

    - by mystify
    I want to achieve something similar to what these guys do here: - (NSUInteger)countForFetchRequest:(NSFetchRequest *)request error:(NSError **)error like you can see, you pass an NSError pointer and that nice method will assign a real NSError object to your pointer in case there is an error. So the cool thing about this is, that the method returns an NSUInteger but can ALSO return an NSError, without having to mess around with ugly and fat arrays or dictionaries. So how could I assign an object to the passed-in error pointer?

    Read the article

  • how to fetch & store any column from coredata to array

    - by user440485
    Hi All, I am working on page(Lesson) has button called "AddToFavorite". when i click on this button lessonID,lessonHeading is added in the Coredata. - (NSFetchedResultsController *)fetchedResultsController { // Set up the fetched results controller if needed. if (fetchedResultsController != nil) { return fetchedResultsController; } // Create the fetch request for the entity. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; // Edit the entity name as appropriate. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Favorites" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // Edit the sort key as appropriate. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lessonHeading" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"lessonHeading" cacheName:@"Root"]; self.fetchedResultsController = aFetchedResultsController; self.fetchedResultsController.delegate = self; [aFetchedResultsController release]; [fetchRequest release]; [sortDescriptor release]; [sortDescriptors release]; return fetchedResultsController; } -(void)addToFavorites { UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"Lesson has been added successfully to your Favorite List" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; //Create a new managed object context for the new book -- set its persistent store coordinator to the same as that from the fetched results controller's context. NSManagedObjectContext *addingContext = [[NSManagedObjectContext alloc] init]; self.addingManagedObjectContext = addingContext; [addingManagedObjectContext setPersistentStoreCoordinator:[[fetchedResultsController managedObjectContext] persistentStoreCoordinator]]; Favorites *fav = [NSEntityDescription insertNewObjectForEntityForName:@"Favorites" inManagedObjectContext:addingContext]; fav.lessonID=[[data objectAtIndex:count]objectForKey:@"LessonID"]; fav.lessonTitle=[[data objectAtIndex:count]objectForKey:@"LessonTitle"]; [self didFinishWithSave:YES]; [addingContext release]; } My problem is that i want to show an alert if this lessonID is already existing in the coreData. show guide me how i can match the current page lessonID with the existing lessonID's in the CoreData. I am using CoreData 1st time.so sory for any mistake ...& thanks for ypur help frnds.

    Read the article

  • Fail to save a managed object to core-data after its properties were updated.

    - by Tzur Gazit
    I have to trouble to create the object, but updating it fails. Here is the creation code: // Save data from pList to core data fro the first time - (void) saveToCoreData:(NSDictionary *)plistDictionary { // Create system parameter entity SystemParameters *systemParametersEntity = (SystemParameters *)[NSEntityDescription insertNewObjectForEntityForName:@"SystemParameters" inManagedObjectContext:mManagedObjectContext]; //// // GPS SIMULATOR //// NSDictionary *GpsSimulator = [plistDictionary valueForKey:@"GpsSimulator"]; [systemParametersEntity setMGpsSimulatorEnabled:[[GpsSimulator objectForKey:@"Enabled"] boolValue]]; [systemParametersEntity setMGpsSimulatorFileName:[GpsSimulator valueForKey:@"FileName"]]; [systemParametersEntity setMGpsSimulatorPlaybackSpeed:[[GpsSimulator objectForKey:@"PlaybackSpeed"] intValue]]; [self saveAction]; } During execution the cached copy is changed and then it is saved (or trying) to the database. Here is the code to save the changed copy: // Save data from pList to core data fro the first time - (void) saveSystemParametersToCoreData:(SystemParameters *)theSystemParameters { // Step 1: Select Data NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"SystemParameters" inManagedObjectContext:mManagedObjectContext]; [fetchRequest setEntity:entity]; NSError *error = nil; NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; [fetchRequest release]; if (error) { NSLog(@"CoreData: saveSystemParametersToCoreData: Unresolved error %@, %@", error, [error userInfo]); abort(); } // Step 2: Update Object SystemParameters *systemParameters = [items objectAtIndex:0]; //// // GPS SIMULATOR //// [systemParameters setMGpsSimulatorEnabled:[theSystemParameters mGpsSimulatorEnabled]]; [systemParameters setMGpsSimulatorFileName:[theSystemParameters mGpsSimulatorFileName]]; [systemParameters setMGpsSimulatorPlaybackSpeed:[theSystemParameters mGpsSimulatorPlaybackSpeed]]; // Step 3: Save Updates [self saveAction]; } As to can see, I fetch the object that I want to update, change its values and save. Here is the saving code: - (void)saveAction { NSError *error; if (![[self mManagedObjectContext] save:&error]) { NSLog(@"ERROR:saveAction. Unresolved Core Data Save error %@, %@", error, [error userInfo]); exit(-1); } } The Persistent store method: - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (mPersistentStoreCoordinator != nil) { return mPersistentStoreCoordinator; } NSString *path = [self databasePath]; NSURL *storeUrl = [NSURL fileURLWithPath:path]; NSError *error = nil; mPersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![mPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return mPersistentStoreCoordinator; } There is no error but the sqLite file is not updated, hence the data is not persistent. Thanks in advance.

    Read the article

  • How to populate a core data store programmatically?

    - by jdmuys
    I have ran out of hairs to pull with a crash in this routine that populates a core data store from a 9000+ line plist file. The crash happened at the very end of the routine inside the call to [managedObjectContext save:&error]. While if I save after every object insertion, the crash doesn't happen. Of course, saving after every object insertion totally kills the performance (from less than a second to many minutes). I modified my code so that it saves every K insertions, and the crash happens as soon as K = 2. The crash is an out-of-bound exception for an NSArray: Serious application error. Exception was caught during Core Data change processing: *** -[NSCFArray objectAtIndex:]: index (1) beyond bounds (1) with userInfo (null) Also maybe relevant, when the exception happen, my fetch result controller controllerDidChangeContent: delegate routine is in the call stack. It simply calls my table view endUpdate routine. I am now running out of ideas. How am I supposed to populate a core data store with a table view? Here is the call stack: #0 0x901ca4e6 in objc_exception_throw #1 0x01d86c3b in +[NSException raise:format:arguments:] #2 0x01d86b9a in +[NSException raise:format:] #3 0x00072cb9 in _NSArrayRaiseBoundException #4 0x00010217 in -[NSCFArray objectAtIndex:] #5 0x002eaaa7 in -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] #6 0x002def02 in -[UITableView endUpdates] #7 0x00004863 in -[AirportViewController controllerDidChangeContent:] at AirportViewController.m:463 #8 0x01c43be1 in -[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] #9 0x0001462a in _nsnote_callback #10 0x01d31005 in _CFXNotificationPostNotification #11 0x00011ee0 in -[NSNotificationCenter postNotificationName:object:userInfo:] #12 0x01ba417d in -[NSManagedObjectContext(_NSInternalNotificationHandling) _postObjectsDidChangeNotificationWithUserInfo:] #13 0x01c03763 in -[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:withDeletions:withUpdates:withRefreshes:] #14 0x01b885ea in -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] #15 0x01bbe728 in -[NSManagedObjectContext save:] #16 0x000039ea in -[AirportViewController populateAirports] at AirportViewController.m:112 Here is the code to the routine. I apologize because a number of lines are probably irrelevant, but I'd rather err on that side. The crash happens the very first time it calls [managedObjectContext save:&error]: - (void) populateAirports { NSBundle *meBundle = [NSBundle mainBundle]; NSString *dbPath = [meBundle pathForResource:@"DuckAirportsBin" ofType:@"plist"]; NSArray *initialAirports = [[NSArray alloc] initWithContentsOfFile:dbPath]; //********************************************************************************* // get existing countries NSMutableDictionary *countries = [[NSMutableDictionary alloc] initWithCapacity:200]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Country" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSError *error = nil; NSArray *values = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; if (!values) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } int numCountries = [values count]; NSLog(@"We have %d countries in store", numCountries); for (Country *aCountry in values) { [countries setObject:aCountry forKey:aCountry.code]; } [fetchRequest release]; //********************************************************************************* // read airports int numAirports = 0; int numUnsavedAirports = 0; #define MAX_UNSAVED_AIRPORTS_BEFORE_SAVE 2 numCountries = 0; for (NSDictionary *anAirport in initialAirports) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *countryCode = [anAirport objectForKey:@"country"]; Country *thatCountry = [countries objectForKey:countryCode]; if (!thatCountry) { thatCountry = [NSEntityDescription insertNewObjectForEntityForName:@"Country" inManagedObjectContext:managedObjectContext]; thatCountry.code = countryCode; thatCountry.name = [anAirport objectForKey:@"country_name"]; thatCountry.population = 0; [countries setObject:thatCountry forKey:countryCode]; numCountries++; NSLog(@"Found %dth country %@=%@", numCountries, countryCode, thatCountry.name); } // now that we have the country, we create the airport Airport *newAirport = [NSEntityDescription insertNewObjectForEntityForName:@"Airport" inManagedObjectContext:managedObjectContext]; newAirport.city = [anAirport objectForKey:@"city"]; newAirport.code = [anAirport objectForKey:@"code"]; newAirport.name = [anAirport objectForKey:@"name"]; newAirport.country_name = [anAirport objectForKey:@"country_name"]; newAirport.latitude = [NSNumber numberWithDouble:[[anAirport objectForKey:@"latitude"] doubleValue]]; newAirport.longitude = [NSNumber numberWithDouble:[[anAirport objectForKey:@"longitude"] doubleValue]]; newAirport.altitude = [NSNumber numberWithDouble:[[anAirport objectForKey:@"altitude"] doubleValue]]; newAirport.country = thatCountry; // [thatCountry addAirportsObject:newAirport]; numAirports++; numUnsavedAirports++; if (numUnsavedAirports >= MAX_UNSAVED_AIRPORTS_BEFORE_SAVE) { if (![managedObjectContext save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } numUnsavedAirports = 0; } [pool release]; }

    Read the article

  • Objective-C woes: cellForRowAtIndexPath crashes.

    - by Mr. McPepperNuts
    I want to the user to be able to search for a record in a DB. The fetch and the results returned work perfectly. I am having a hard time setting the UItableview to display the result tho. The application continually crashes at cellForRowAtIndexPath. Please, someone help before I have a heart attack over here. Thank you. @implementation SearchViewController @synthesize mySearchBar; @synthesize textToSearchFor; @synthesize myGlobalSearchObject; @synthesize results; @synthesize tableView; @synthesize tempString; #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { [super viewDidLoad]; } #pragma mark - #pragma mark Table View - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //handle selection; push view } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ /* if(nullResulSearch == TRUE){ return 1; }else { return[results count]; } */ return[results count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; // Test hack to display multiple rows. } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Search Cell Identifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil){ cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease]; } NSLog(@"TEMPSTRING %@", tempString); cell.textLabel.text = tempString; return cell; } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; } - (void)viewDidUnload { self.tableView = nil; } - (void)dealloc { [results release]; [mySearchBar release]; [textToSearchFor release]; [myGlobalSearchObject release]; [super dealloc]; } #pragma mark - #pragma mark Search Function & Fetch Controller - (NSManagedObject *)SearchDatabaseForText:(NSString *)passdTextToSearchFor{ NSManagedObject *searchObj; UndergroundBaseballAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == [c]%@", passdTextToSearchFor]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:managedObjectContext]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [request setEntity: entity]; [request setPredicate: predicate]; NSError *error; results = [managedObjectContext executeFetchRequest:request error:&error]; if([results count] == 0){ NSLog(@"No results found"); searchObj = nil; nullResulSearch == TRUE; }else{ if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0) { NSLog(@"results %@", [[results objectAtIndex:0] name]); searchObj = [results objectAtIndex:0]; nullResulSearch == FALSE; }else{ NSLog(@"No results found"); searchObj = nil; nullResulSearch == TRUE; } } [tableView reloadData]; [request release]; [sortDescriptors release]; return searchObj; } - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ textToSearchFor = mySearchBar.text; NSLog(@"textToSearchFor: %@", textToSearchFor); myGlobalSearchObject = [self SearchDatabaseForText:textToSearchFor]; NSLog(@"myGlobalSearchObject: %@", myGlobalSearchObject); tempString = [myGlobalSearchObject valueForKey:@"name"]; NSLog(@"tempString: %@", tempString); } @end *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UILongPressGestureRecognizer isEqualToString:]: unrecognized selector sent to instance 0x3d46c20'

    Read the article

  • [UIView didCreateWorkout:Type:Distance:Time:Message:]: unrecognized selector sent to instance.

    - by Stephen
    Hello, I'm getting the above error and have been looking at it all day, I'm getting no where fast. Anyone any ideas ? I'm new to IPhone Development. Code Below: #import "WorkoutViewController.h" #import "Workout.h" @implementation WorkoutViewController @synthesize workoutDelegate; //@synthesize Speed; //@synthesize Calories; @synthesize route; @synthesize type; @synthesize distance; @synthesize time; @synthesize message; @synthesize DBContents; @synthesize workoutArray; @synthesize managedObjectContext; //@synthesize saveWorkout; //@synthesize cancelWorkout; -(IBAction)hideKeyboard { } -(IBAction)saveWorkout { [workoutDelegate didCreateWorkout: route.text Type: type.text Distance: distance.text Time: time.text Message: message.text]; } -(IBAction)cancelWorkout { [self.workoutDelegate didCancelWorkout]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -(void)viewDidLoad { //Set images for Save & Cancel buttons. UIImage *normalImage = [[UIImage imageNamed:@"whiteButton.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0]; [saveWorkout setBackgroundImage:normalImage forState:UIControlStateNormal]; [cancelWorkout setBackgroundImage:normalImage forState:UIControlStateNormal]; UIImage *pressedImage = [[UIImage imageNamed:@"blueButton.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0]; [saveWorkout setBackgroundImage:pressedImage forState:UIControlStateHighlighted]; [cancelWorkout setBackgroundImage:pressedImage forState:UIControlStateHighlighted]; //Fetch details from the database. NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Workout" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSError *error; self.workoutArray = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; [request release]; //self.workoutArray = [[NSMutableArray alloc] init]; //self.DBContents.text = [self.workoutArray objectAtIndex:0]; [super viewDidLoad]; } -(void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } -(void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } -(void) didCreateWorkout:(NSString *)thisRoute Type:(NSString *)thisType Distance:(NSString *)thisDistance Time:(NSString *)thisTime Message:(NSString *)thisMessage { // Add the new workout. Workout *newWorkout = [NSEntityDescription insertNewObjectForEntityForName:@"Workout" inManagedObjectContext:self.managedObjectContext]; newWorkout.route = thisRoute; newWorkout.type = thisType; newWorkout.distance = thisDistance; newWorkout.time = thisTime; newWorkout.message = thisMessage; [self.workoutArray addObject:newWorkout]; //[self dismissModalViewControllerAnimated:YES]; } -(void)didCancelWorkout { [self dismissModalViewControllerAnimated:YES]; } -(void)dealloc { // [Speed release]; // [Calories release]; [route release]; [type release]; [distance release]; [time release]; [message release]; // [saveWorkout release]; // [cancelWorkout release]; [workoutArray release]; [managedObjectContext release]; [super dealloc]; } @end I'm trying to save details that I key on the screen (WorkoutViewController.xib) and I click the save button and get the above error. Thanks Stephen

    Read the article

  • Objective-C: Scope problems cellForRowAtIndexPath

    - by Mr. McPepperNuts
    How would I set each individual row in cellForRowAtIndexPath to the results of an array populated by a Fetch Request? (Fetch Request made when button is pressed.) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // ... set up cell code here ... cell.textLabel.text = [results objectAtIndex:indexPath valueForKey:@"name"]; } warning: 'NSArray' may not respond to '-objectAtIndexPath:' Edit: - (NSArray *)SearchDatabaseForText:(NSString *)passdTextToSearchFor{ NSManagedObject *searchObj; XYZAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains [cd] %@", passdTextToSearchFor]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:managedObjectContext]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [request setEntity: entity]; [request setPredicate: predicate]; NSError *error; results = [managedObjectContext executeFetchRequest:request error:&error]; // NSLog(@"results %@", results); if([results count] == 0){ NSLog(@"No results found"); searchObj = nil; self.tempString = @"No results found."; }else{ if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0) { NSLog(@"results %@", [[results objectAtIndex:0] name]); searchObj = [results objectAtIndex:0]; }else{ NSLog(@"No results found"); self.tempString = @"No results found."; searchObj = nil; } } [tableView reloadData]; [request release]; [sortDescriptors release]; return results; } - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ textToSearchFor = mySearchBar.text; results = [self SearchDatabaseForText:textToSearchFor]; self.tempString = [myGlobalSearchObject valueForKey:@"name"]; NSLog(@"results count: %d", [results count]); NSLog(@"results 0: %@", [[results objectAtIndex:0] name]); NSLog(@"results 1: %@", [[results objectAtIndex:1] name]); } @end Console prints: 2010-06-10 16:11:18.581 XYZApp[10140:207] results count: 2 2010-06-10 16:11:18.581 XYZApp[10140:207] results 0: BB Bugs 2010-06-10 16:11:18.582 XYZApp[10140:207] results 1: BB Annie Program received signal: “EXC_BAD_ACCESS”. (gdb) Edit 2: BT: #0 0x95a91edb in objc_msgSend () #1 0x03b1fe20 in ?? () #2 0x0043cd2a in -[UITableViewRowData(UITableViewRowDataPrivate) _updateNumSections] () #3 0x0043ca9e in -[UITableViewRowData invalidateAllSections] () #4 0x002fc82f in -[UITableView(_UITableViewPrivate) _updateRowData] () #5 0x002f7313 in -[UITableView noteNumberOfRowsChanged] () #6 0x00301500 in -[UITableView reloadData] () #7 0x00008623 in -[SearchViewController SearchDatabaseForText:] (self=0x3d16190, _cmd=0xf02b, passdTextToSearchFor=0x3b29630) #8 0x000086ad in -[SearchViewController searchBarSearchButtonClicked:] (self=0x3d16190, _cmd=0x16492cc, searchBar=0x3d2dc50) #9 0x0047ac13 in -[UISearchBar(UISearchBarStatic) _searchFieldReturnPressed] () #10 0x0031094e in -[UIControl(Deprecated) sendAction:toTarget:forEvent:] () #11 0x00312f76 in -[UIControl(Internal) _sendActionsForEventMask:withEvent:] () #12 0x0032613b in -[UIFieldEditor webView:shouldInsertText:replacingDOMRange:givenAction:] () #13 0x01d5a72d in __invoking___ () #14 0x01d5a618 in -[NSInvocation invoke] () #15 0x0273fc0a in SendDelegateMessage () #16 0x033168bf in -[_WebSafeForwarder forwardInvocation:] () #17 0x01d7e6f4 in ___forwarding___ () #18 0x01d5a6c2 in __forwarding_prep_0___ () #19 0x03320fd4 in WebEditorClient::shouldInsertText () #20 0x0279dfed in WebCore::Editor::shouldInsertText () #21 0x027b67a5 in WebCore::Editor::insertParagraphSeparator () #22 0x0279d662 in WebCore::EventHandler::defaultTextInputEventHandler () #23 0x0276cee6 in WebCore::EventTargetNode::defaultEventHandler () #24 0x0276cb70 in WebCore::EventTargetNode::dispatchGenericEvent () #25 0x0276c611 in WebCore::EventTargetNode::dispatchEvent () #26 0x0279d327 in WebCore::EventHandler::handleTextInputEvent () #27 0x0279d229 in WebCore::Editor::insertText () #28 0x03320f4d in -[WebHTMLView(WebNSTextInputSupport) insertText:] () #29 0x0279d0b4 in -[WAKResponder tryToPerform:with:] () #30 0x03320a33 in -[WebView(WebViewEditingActions) _performResponderOperation:with:] () #31 0x03320990 in -[WebView(WebViewEditingActions) insertText:] () #32 0x00408231 in -[UIWebDocumentView insertText:] () #33 0x003ccd31 in -[UIKeyboardImpl acceptWord:firstDelete:addString:] () #34 0x003d2c8c in -[UIKeyboardImpl addInputString:fromVariantKey:] () #35 0x004d1a00 in -[UIKeyboardLayoutStar sendStringAction:forKey:] () #36 0x004d0285 in -[UIKeyboardLayoutStar handleHardwareKeyDownFromSimulator:] () #37 0x002b5bcb in -[UIApplication handleEvent:withNewEvent:] () #38 0x002b067f in -[UIApplication sendEvent:] () #39 0x002b7061 in _UIApplicationHandleEvent () #40 0x02542d59 in PurpleEventCallback () #41 0x01d55b80 in CFRunLoopRunSpecific () #42 0x01d54c48 in CFRunLoopRunInMode () #43 0x02541615 in GSEventRunModal () #44 0x025416da in GSEventRun () #45 0x002b7faf in UIApplicationMain () #46 0x00002578 in main (argc=1, argv=0xbfffef5c) at /Users/default/Documents/iPhone Projects/XYZApp/main.m:14

    Read the article

  • Broken Multithreading With Core Data

    - by spamguy
    This is a better-focused version of an earlier question that touches upon an entirely different subject from before. I am working on a Cocoa Core Data application with multiple threads. There is a Song and Artist; every Song has an Artist relation. There is a delegate code file not cited here; it more or less looks like the template XCode generates. I am far better working with the former technology than the latter, and any multithreading capability came from a Core Data template. When I'm doing all my ManagedObjectContext work in one method, I am fine. When I put fetch-or-insert-then-return-object work into a separate method, the application halts (but does not crash) at the new method's return statement, seen below. The new method even gets its own MOC to be safe, and it has not helped any. The result is one addition to Song and a halt after generating an Artist. I get no errors or exceptions, and I don't know why. I've debugged out the wazoo. My theory is that any errors occurring are in another thread, and the one I'm watching is waiting on something forever. What did I do wrong with getArtistObject: , and how can I fix it? Thanks. - (void)main { NSInteger songCount = 1; NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init]; [moc setPersistentStoreCoordinator:[[self delegate] persistentStoreCoordinator]]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:moc]; /* songDict generated here */ for (id key in songDict) { NSManagedObject *song = [NSEntityDescription insertNewObjectForEntityForName:@"Song" inManagedObjectContext:moc]; [song setValue:[songDictItem objectForKey:@"Name"] forKey:@"title"]; [song setValue:[self getArtistObject:(NSString *) [songDictItem objectForKey:@"Artist"]] forKey:@"artist"]; [songDictItem release]; songCount++; } NSError *error; if (![moc save:&error]) [NSApp presentError:error]; [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:moc]; [moc release], moc = nil; [[self delegate] importDone]; } - (NSManagedObject*) getArtistObject:(NSString*)theArtist { NSError *error = nil; NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init]; [moc setPersistentStoreCoordinator:[[self delegate] persistentStoreCoordinator]]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:moc]; NSFetchRequest *fetch = [[[NSFetchRequest alloc] init] autorelease]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Artist" inManagedObjectContext:moc]; [fetch setEntity:entityDescription]; // object to be returned NSManagedObject *artistObject = [[NSManagedObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:moc]; // set predicate (artist name) NSPredicate *pred = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name = \"%@\"", theArtist]]; [fetch setPredicate:pred]; NSArray *response = [moc executeFetchRequest:fetch error:&error]; if (error) [NSApp presentError:error]; if ([response count] == 0) // empty resultset --> no artists with this name { [artistObject setValue:theArtist forKey:@"name"]; NSLog(@"%@ not found. Adding.", theArtist); return artistObject; } else return [response objectAtIndex:0]; } @end

    Read the article

  • UILabels NOT Updating

    - by Chris Calleja Urry
    i have a UITableView that is being populated by core data , now , when i click on a cell , it pushes me to another view where i can edit the data that is in that particular index , when i return , the system either crashes or else doesnt load the changes onto the labels , any ideas ? code below -(void)viewWillAppear:(BOOL)animated { searchCriteria = [[NSMutableString alloc] initWithString:@"clientName"]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"clientName" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Client" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; [self.clientTableView reloadData]; [super viewWillAppear:animated]; } and -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } Client * client = [self.fetchedResultsController objectAtIndexPath:indexPath]; clientNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 250.00, 30.0)]; clientNameLabel.tag = 1; clientNameLabel.backgroundColor = [UIColor clearColor]; clientNameLabel.textColor = [UIColor whiteColor]; clientNameLabel.font = [UIFont boldSystemFontOfSize:13]; clientNameLabel.text = client.clientName; [cell.contentView addSubview:clientNameLabel]; clientAccountNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(15.0, 35.0, 250.00, 30.00)]; clientAccountNumberLabel.tag = 2; clientAccountNumberLabel.textColor = [UIColor whiteColor]; clientAccountNumberLabel.backgroundColor = [UIColor clearColor]; clientAccountNumberLabel.font = [UIFont boldSystemFontOfSize:13]; clientAccountNumberLabel.text = client.clientAccountNumber; [cell.contentView addSubview:clientAccountNumberLabel]; clientTelephoneNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(300.0, 0.0, 250, 30.00)]; clientTelephoneNumberLabel.tag = 3; clientTelephoneNumberLabel.textColor = [UIColor whiteColor]; clientTelephoneNumberLabel.backgroundColor = [UIColor clearColor]; clientTelephoneNumberLabel.font = [UIFont boldSystemFontOfSize:13]; [cell.contentView addSubview:clientTelephoneNumberLabel]; addressLine1Label = [[UILabel alloc] initWithFrame:CGRectMake(315.0, 35.0, 250, 30.00)]; addressLine1Label.tag = 4; addressLine1Label.textColor = [UIColor whiteColor]; addressLine1Label.backgroundColor = [UIColor clearColor]; addressLine1Label.font = [UIFont boldSystemFontOfSize:13]; addressLine1Label.text = client.addressLine1; [cell.contentView addSubview:addressLine1Label]; addressLine2Label = [[UILabel alloc] initWithFrame:CGRectMake(315.0, 35.0, 250, 30.00)]; addressLine2Label.tag = 5; addressLine2Label.textColor = [UIColor whiteColor]; addressLine2Label.backgroundColor = [UIColor clearColor]; addressLine2Label.text = client.addressLine2; addressLine2Label.font = [UIFont boldSystemFontOfSize:13]; [cell.contentView addSubview:addressLine2Label]; addressLine3Label = [[UILabel alloc] initWithFrame:CGRectMake(315.0, 35.0, 250, 30.00)]; addressLine3Label.tag = 6; addressLine3Label.textColor = [UIColor whiteColor]; addressLine3Label.backgroundColor = [UIColor clearColor]; addressLine3Label.font = [UIFont boldSystemFontOfSize:13]; addressLine3Label.text = client.addressLine3; [cell.contentView addSubview:addressLine3Label]; addressLine4Label = [[UILabel alloc] initWithFrame:CGRectMake(315.0, 35.0, 250, 30.00)]; addressLine4Label.tag = 7; addressLine4Label.textColor = [UIColor whiteColor]; addressLine4Label.backgroundColor = [UIColor clearColor]; addressLine4Label.font = [UIFont boldSystemFontOfSize:13]; addressLine4Label.text = client.addressLine4; [cell.contentView addSubview:addressLine4Label]; return cell; } The Crash Logs are as follows : 2012-06-23 17:08:05.541 iSalesForce[11773:15803] no object at index 1 in section at index 0 And some other code you might find useful are : - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [fetchedObjects count]; } - (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 70.0; }

    Read the article

  • Return NSArray from NSDictionary

    - by Jon
    I have a fetch that returns an array with dictionary in it of an attribute of a core data object. Here is my previous question: Create Array From Attribute of NSObject From NSFetchResultsController This is the fetch: NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entity]; [request setResultType:NSDictionaryResultType]; [request setReturnsDistinctResults:NO]; //set to YES if you only want unique values of the property [request setPropertiesToFetch :[NSArray arrayWithObject:@"timeStamp"]]; //name(s) of properties you want to fetch // Execute the fetch. NSError *error; NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error]; When I log the NSArray data, I get this: The content of data is( { timeStamp = "2011-06-14 21:30:03 +0000"; }, { timeStamp = "2011-06-16 21:00:18 +0000"; }, { timeStamp = "2011-06-11 21:00:18 +0000"; }, { timeStamp = "2011-06-23 19:53:35 +0000"; }, { timeStamp = "2011-06-21 19:53:35 +0000"; } ) What I want is an array with this format: [NSArray arrayWithObjects: @"2011-11-01 00:00:00 +0000", @"2011-12-01 00:00:00 +0000", nil];' Edit: This is the method for which I want to replace the data array with my new data array: - (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate { NSLog(@"calendarMonthView marksFromDate toDate"); NSLog(@"Make sure to update 'data' variable to pull from CoreData, website, User Defaults, or some other source."); // When testing initially you will have to update the dates in this array so they are visible at the // time frame you are testing the code. NSArray *data = [NSArray arrayWithObjects: @"2011-01-01 00:00:00 +0000", @"2011-12-01 00:00:00 +0000", nil]; // Initialise empty marks array, this will be populated with TRUE/FALSE in order for each day a marker should be placed on. NSMutableArray *marks = [NSMutableArray array]; // Initialise calendar to current type and set the timezone to never have daylight saving NSCalendar *cal = [NSCalendar currentCalendar]; [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; // Construct DateComponents based on startDate so the iterating date can be created. // Its massively important to do this assigning via the NSCalendar and NSDateComponents because of daylight saving has been removed // with the timezone that was set above. If you just used "startDate" directly (ie, NSDate *date = startDate;) as the first // iterating date then times would go up and down based on daylight savings. NSDateComponents *comp = [cal components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) fromDate:startDate]; NSDate *d = [cal dateFromComponents:comp]; // Init offset components to increment days in the loop by one each time NSDateComponents *offsetComponents = [[NSDateComponents alloc] init]; [offsetComponents setDay:1]; // for each date between start date and end date check if they exist in the data array while (YES) { // Is the date beyond the last date? If so, exit the loop. // NSOrderedDescending = the left value is greater than the right if ([d compare:lastDate] == NSOrderedDescending) { break; } // If the date is in the data array, add it to the marks array, else don't if ([data containsObject:[d description]]) { [marks addObject:[NSNumber numberWithBool:YES]]; } else { [marks addObject:[NSNumber numberWithBool:NO]]; } // Increment day using offset components (ie, 1 day in this instance) d = [cal dateByAddingComponents:offsetComponents toDate:d options:0]; } [offsetComponents release]; return [NSArray arrayWithArray:marks]; }

    Read the article

  • tableView:didSelectRowAtIndexPath: calls TTNavigator openURLAction:applyAnimated: — UITabBar and na

    - by vikingosegundo
    I have an existing iphone project with a UITabBar. Now I need styled text and in-text links to other ViewControllers in my app. I am trying to integrate TTStyledTextLabel. I have a FirstViewController:UITabelViewController with this tableView:didSelectRowAtIndexPath: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString *url; if ([self.filteredQuestions count]>0) { url = [NSString stringWithFormat:@"%@%d", @"tt://question/", [[self.filteredQuestions objectAtIndex:indexPath.row] id]]; [[TTNavigator navigator] openURLAction:[[TTURLAction actionWithURLPath: url] applyAnimated:YES]]; } else { Question * q = [self.questions objectAtIndex:indexPath.row] ; url = [NSString stringWithFormat:@"%@%d", @"tt://question/", [q.id intValue]]; } TTDPRINT(@"%@", url); TTNavigator *navigator = [TTNavigator navigator]; [navigator openURLAction:[[TTURLAction actionWithURLPath: url] applyAnimated:YES]]; } My mapping looks like this: TTNavigator* navigator = [TTNavigator navigator]; navigator.window = window; navigator.supportsShakeToReload = YES; TTURLMap* map = navigator.URLMap; [map from:@"*" toViewController:[TTWebController class]]; [map from:@"tt://question/(initWithQID:)" toViewController:[QuestionDetailViewController class]]; and my QuestionDetailViewController: @interface QuestionDetailViewController : UIViewController <UIScrollViewDelegate , QuestionDetailViewProtocol> { Question *question; } @property(nonatomic,retain) Question *question; -(id) initWithQID:(NSString *)qid; -(void) goBack:(id)sender; @end When I hit a cell, q QuestionDetailViewController will be called — but the navigationBar wont @implementation QuestionDetailViewController @synthesize question; -(id) initWithQID:(NSString *)qid { if (self = [super initWithNibName:@"QuestionDetailViewController" bundle:nil]) { //; TTDPRINT(@"%@", qid); NSManagedObjectContext *managedObjectContext = [(domainAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext]; NSPredicate *predicate =[NSPredicate predicateWithFormat:@"id == %@", qid]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entity]; [request setPredicate:predicate]; NSError *error = nil; NSArray *array = [managedObjectContext executeFetchRequest:request error:&error]; if (error==nil && [array count]>0 ) { self.question = [array objectAtIndex:0]; } else { TTDPRINT(@"error: %@", array); } } return self; } - (void)viewDidLoad { [super viewDidLoad]; [TTStyleSheet setGlobalStyleSheet:[[[TextTestStyleSheet alloc] init] autorelease]]; [self.navigationController.navigationBar setTranslucent:YES]; NSArray *includedLinks = [self.question.answer.text vs_extractExternalLinks]; NSMutableDictionary *linksToTT = [[NSMutableDictionary alloc] init]; for (NSArray *a in includedLinks) { NSString *s = [a objectAtIndex:3]; if ([s hasPrefix:@"/answer/"] || [s hasPrefix:@"http://domain.com/answer/"] || [s hasPrefix:@"http://www.domain.com/answer/"]) { NSString *ttAdress = @"tt://question/"; NSArray *adressComps = [s pathComponents]; for (NSString *s in adressComps) { if ([s isEqualToString:@"qid"]) { ttAdress = [ttAdress stringByAppendingString:[adressComps objectAtIndex:[adressComps indexOfObject:s]+1]]; } } [linksToTT setObject:ttAdress forKey:s]; } } for (NSString *k in [linksToTT allKeys]) { self.question.answer.text = [self.question.answer.text stringByReplacingOccurrencesOfString:k withString: [linksToTT objectForKey:k]]; } TTStyledTextLabel *answerText = [[[TTStyledTextLabel alloc] initWithFrame:CGRectMake(0, 0, 320, 700)] autorelease]; if (![[self.question.answer.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] hasPrefix:@"<div"]) { self.question.answer.text = [NSString stringWithFormat:@"%<div>%@</div>", self.question.answer.text]; } NSString * s = [NSString stringWithFormat:@"<div class=\"header\">%@</div>\n%@",self.question.title ,self.question.answer.text]; answerText.text = [TTStyledText textFromXHTML:s lineBreaks:YES URLs:YES]; answerText.contentInset = UIEdgeInsetsMake(20, 15, 20, 15); [answerText sizeToFit]; [self.navigationController setNavigationBarHidden:NO animated:YES]; [self.view addSubview:answerText]; [(UIScrollView *)self.view setContentSize:answerText.frame.size]; self.view.backgroundColor = [UIColor whiteColor]; [linksToTT release]; } ....... @end This works quite nice, as soon as a cell is touched, a QuestionDetailViewController is called and pushed — but the tabBar will disappear, and the navigationItem — I set it like this: self.navigationItem.title =@"back to first screen"; — won't be shown. And it just appears without animation. But if I press a link inside the TTStyledTextLabel the animation works, the navigationItem will be shown. How can I make the animation, the navigationItem and the tabBar be shown?

    Read the article

  • Crash when trying to get NSManagedObject from NSFetchedResultsController after 25 objects?

    - by Jeremy
    Hey everyone, I'm relatively new to Core Data on iOS, but I think I've been getting better with it. I've been experiencing a bizarre crash, however, in one of my applications and have not been able to figure it out. I have approximately 40 objects in Core Data, presented in a UITableView. When tapping on a cell, a UIActionSheet appears, presenting the user with a UIActionSheet with options related to the cell that was selected. So that I can reference the selected object, I declare an NSIndexPath in my header called "lastSelection" and do the following when the UIActionSheet is presented: // Each cell has a tag based on its row number (i.e. first row has tag 0) lastSelection = [NSIndexPath indexPathForRow:[sender tag] inSection:0]; NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:lastSelection]; BOOL onDuty = [[managedObject valueForKey:@"onDuty"] boolValue]; UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Status" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; if(onDuty) { [actionSheet addButtonWithTitle:@"Off Duty"]; } else { [actionSheet addButtonWithTitle:@"On Duty"]; } actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque; // Override the typical UIActionSheet behavior by presenting it overlapping the sender's frame. This makes it more clear which cell is selected. CGRect senderFrame = [sender frame]; CGPoint point = CGPointMake(senderFrame.origin.x + (senderFrame.size.width / 2), senderFrame.origin.y + (senderFrame.size.height / 2)); CGRect popoverRect = CGRectMake(point.x, point.y, 1, 1); [actionSheet showFromRect:popoverRect inView:[sender superview] animated:NO]; [actionSheet release]; When the UIActionSheet is dismissed with a button, the following code is called: - (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex { // Set status based on UIActionSheet button pressed if(buttonIndex == -1) { return; } NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:lastSelection]; if([actionSheet.title isEqualToString:@"Status"]) { if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"On Duty"]) { [managedObject setValue:[NSNumber numberWithBool:YES] forKey:@"onDuty"]; [managedObject setValue:@"onDuty" forKey:@"status"]; } else { [managedObject setValue:[NSNumber numberWithBool:NO] forKey:@"onDuty"]; [managedObject setValue:@"offDuty" forKey:@"status"]; } } NSError *error; [self.managedObjectContext save:&error]; [tableView reloadData]; } This might not be the most efficient code (sorry, I'm new!), but it does work. That is, for the first 25 items in the list. Selecting the 26th item or beyond, the UIActionSheet will appear, but if it is dismissed with a button, I get a variety of errors, including any one of the following: [__NSCFArray section]: unrecognized selector sent to instance 0x4c6bf90 Program received signal: “EXC_BAD_ACCESS” [_NSObjectID_48_0 section]: unrecognized selector sent to instance 0x4c54710 [__NSArrayM section]: unrecognized selector sent to instance 0x4c619a0 [NSComparisonPredicate section]: unrecognized selector sent to instance 0x6088790 [NSKeyPathExpression section]: unrecognized selector sent to instance 0x4c18950 If I comment out NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:lastSelection]; it doesn't crash anymore, so I believe it has something do do with that. Can anyone offer any insight? Please let me know if I need to include any other information. Thanks! EDIT: Interestingly, my fetchedResultsController code returns a different object every time. Is this expected, or could this be a cause of my issue? The code looks like this: - (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:@"Employee" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Set the batch size to a suitable number. [fetchRequest setFetchBatchSize:80]; // Edit the sort key as appropriate. NSString *sortKey; BOOL ascending; if(sortControl.selectedSegmentIndex == 0) { sortKey = @"startTime"; ascending = YES; } else if(sortControl.selectedSegmentIndex == 1) { sortKey = @"name"; ascending = YES; } else { sortKey = @"onDuty"; ascending = NO; } NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:ascending]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Edit the section name key path and cache name if appropriate. NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; [aFetchedResultsController release]; [fetchRequest release]; [sortDescriptor release]; [sortDescriptors release]; NSError *error = nil; if (![fetchedResultsController_ performFetch:&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. */ //NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return fetchedResultsController_; } This happens when I set a breakpoint: (gdb) po [self fetchedResultsController] <NSFetchedResultsController: 0x61567c0> (gdb) po [self fetchedResultsController] <NSFetchedResultsController: 0x4c83630>

    Read the article

  • Problem with entityForName & ManagedObjectContext when extending tutorial material

    - by Martin KS
    Afternoon all, I tried to add a second data entity to the persistent store in the (locations) coredata tutorial code, and then access this in a new view. I think that I've followed the tutorial, and checked that I'm doing a clean build etc, but can't see what to change to prevent it crashing. I'm afraid I'm at my wits end with this one, and can't seem to find the step that I've missed. I've pasted the header and code files below, please let me know if I need to share any more of the code. The crash seems to happen on the line: NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:[self managedObjectContext]]; There is one other line in the code that refers to galleryviewcontroller at the moment, and that's in the main application delegate: galleryViewController.managedObjectContext = [self managedObjectContext]; GalleryViewController.h #import <UIKit/UIKit.h> @interface GalleryViewController : UIViewController { NSManagedObjectContext *managedObjectContext; int rowNumber; IBOutlet UILabel *lblMessage; UIBarButtonItem *addButton; NSMutableArray *imagesArray; } @property (readwrite) int rowNumber; @property (nonatomic,retain) UILabel *lblMessage; @property (nonatomic,retain) NSMutableArray *imagesArray; @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain) UIBarButtonItem *addButton; -(void)updateRowNumber:(int)theIndex; -(void)addImage; @end GalleryViewController.m #import "RootViewController.h" #import "LocationsAppDelegate.h" #import "Album.h" #import "GalleryViewController.h" #import "Image.h" @implementation GalleryViewController @synthesize lblMessage,rowNumber,addButton,managedObjectContext; @synthesize imagesArray; /* // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Custom initialization } return self; } */ -(void)updateRowNumber:(int)theIndex{ rowNumber=theIndex; LocationsAppDelegate *mainDelegate =(LocationsAppDelegate *)[[UIApplication sharedApplication] delegate]; Album *anAlbum = [mainDelegate.albumsArray objectAtIndex:rowNumber]; lblMessage.text = anAlbum.uniqueAlbumIdentifier; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addImage)]; addButton.enabled = YES; self.navigationItem.rightBarButtonItem = addButton; /* Found this in another answer, adding it to the code didn't help. if (managedObjectContext == nil) { managedObjectContext = [[[UIApplication sharedApplication] delegate] managedObjectContext]; } */ NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:[self managedObjectContext]]; [request setEntity:entity]; // Order the albums by creation date, most recent first. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"imagePath" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [sortDescriptor release]; [sortDescriptors release]; // Execute the fetch -- create a mutable copy of the result. NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. } [self setImagesArray:mutableFetchResults]; int a = 5; int b = 10; for( int i=0; i<[imagesArray count]; i++ ) { if( a == 325 ) { a = 5; b += 70; } UIImageView *any = [[UIImageView alloc] initWithFrame:CGRectMake(a,b,70,60)]; any.image = [imagesArray objectAtIndex:i]; any.tag = i; [self.view addSubview:any]; [any release]; a += 80; } } -(void)addImage{ NSString *msg = [NSString stringWithFormat:@"%i",rowNumber]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add image to" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil]; [alert show]; [alert release]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { [super viewDidUnload]; } - (void)dealloc { [lblMessage release]; [managedObjectContext release]; [super dealloc]; } @end

    Read the article

  • Does the Fetch Request do the recommended batch faulting?

    - by dontWatchMyProfile
    I'm curious. Apple says in the docs: Core Data automatically fires faults when necessary (when a persistent property of a fault is accessed). However, firing faults individually can be inefficient, and there are better strategies for getting data from the persistent store (see “Batch Faulting and Pre-fetching with the SQLite Store”). NSFetchRequest has this feature: [fetchRequest setFetchBatchSize:20]; Is this essentially performing such a batch faulting like recommended? Just to make this clear for others, faulting does not mean "turning into a fault" but it means "materializing it", just like "making a Scooby-Doo out of it". Pretty ugly wording error, in my opinion, but it's at least consistent in the docs ;)

    Read the article

  • NSFetchedResultsController doesn't fetch up the child-parent moc chain?

    - by Kronusdark
    I cannot find any clarification on this, so it may be a bug. Problem is, I have a series of parent-child Managed Object Context's. When I save on a child context the changes get pushed up to the parent, and I can fetch using a plain old NSFetchRequest. However, if I rely on an NSFetchedResultsController to pull these changes into a sibling context to the first, they do not see them. calling -(void)performFetch: error; doesn't seem to pull the changes either. After a restart of the app, all new data is available. My hypothesis is that NSFetchedResultsController only fetches from its current context and will not follow the chain to the persistent store. Can someone please set me straight here? Am I going to have to use notifications to monitor changes on other contexts? and finally, is this mentioned somewhere in the doc's? I cannot find it for the life of me.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >