Search Results

Search found 124 results on 5 pages for 'nspredicate'.

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

  • getting record from CoreData ?

    - by Meko
    Hi. I am trying to add value to CoreData from .plist and get from coreData and show them on UITable. I made take from .plist and send them to CoreData .But I cant take them from CoreData entity and set to some NSMutable array.. Here my codes Edit : SOLVED NSString *path = [[NSBundle mainBundle] pathForResource:@"FakeData" ofType:@"plist"]; NSArray *myArray=[[NSArray alloc] initWithContentsOfFile:path]; FlickrFetcher *flickrfetcher =[FlickrFetcher sharedInstance]; managedObjectContext =[flickrfetcher managedObjectContext]; for(NSDictionary *dict in myArray){ Photo *newPhoto = (Photo *)[NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:managedObjectContext]; // set the attributes for the photo NSLog(@"Creating Photo: %@", [dict objectForKey:@"name"]); [newPhoto setName:[dict objectForKey:@"name"]]; [newPhoto setPath:[dict objectForKey:@"path"]]; NSLog(@"Person is: %@", [dict objectForKey:@"user"]); NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name ==%@",[dict objectForKey:@"user"]]; NSMutableArray *peopleArray = (NSMutableArray *)[flickrfetcher fetchManagedObjectsForEntity:@"Person" withPredicate:predicate]; NSEnumerator *enumerator = [peopleArray objectEnumerator]; Person *person; BOOL exists = FALSE; while (person = [enumerator nextObject]) { NSLog(@" Person is: %@ ", person.name); if([person.name isEqualToString:[dict objectForKey:@"user"]]) { exists = TRUE; NSLog(@"-- Person Exists : %@--", person.name); [newPhoto setPerson:person]; } } // if person does not already exist then add the person if (!exists) { Person *newPerson = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext]; // create the person [newPerson setName:[dict objectForKey:@"user"]]; NSLog(@"-- Person Created : %@--", newPerson.name); // associate the person with the photo [newPhoto setPerson:newPerson]; } //THis IS myArray that I want to save value in it and them show them in UITABLE personList=[[NSMutableArray alloc]init]; NSLog(@"lllll %@",[personList objectAtIndex:0]); // save the data NSError *error; if (![managedObjectContext save:&error]) { // Handle the error. NSLog(@"Unresolved error %@, %@", error, [error userInfo]); exit(-1); } } //To access core data objects you can try the following: // setup our fetchedResultsController fetchedResultsController = [flickrfetcher fetchedResultsControllerForEntity:@"Person" withPredicate:nil]; // execute the fetch NSError *error; BOOL success = [fetchedResultsController performFetch:&error]; if (!success) { // Handle the error. NSLog(@"Unresolved error %@, %@", error, [error userInfo]); exit(-1); } // save our data //HERE PROBLEM THAT I DONW KNOW WHERE IT IS SAVING //[personList addObject:(NSMutableArray *)[fetchedResultsController fetchedObjects]]; [self setPersonList:(NSMutableArray *)[fetchedResultsController fetchedObjects]]; } Here my tableview function - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"ss %d",[personList count]); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } cell.textLabel.text=[personList objectAtIndex:indexPath.row]; // Set up the cell... return cell; }

    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

  • NSFetchedResultsController: using of NSManagedObjectContext during update brings to crash

    - by Kentzo
    Here is the interface of my controller class: @interface ProjectListViewController : UITableViewController <NSFetchedResultsControllerDelegate> { NSFetchedResultsController *fetchedResultsController; NSManagedObjectContext *managedObjectContext; } @end I use following code to init fetchedResultsController: if (fetchedResultsController != nil) { return fetchedResultsController; } // Create and configure a fetch request with the Project entity. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // Create the sort descriptors array. NSSortDescriptor *projectIdDescriptor = [[NSSortDescriptor alloc] initWithKey:@"projectId" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:projectIdDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Create and initialize the fetch results controller. NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil]; self.fetchedResultsController = aFetchedResultsController; fetchedResultsController.delegate = self; As you can see, I am using the same managedObjectContext as defined in my controller class Here is an adoption of the NSFetchedResultsControllerDelegate protocol: - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { // The fetch controller is about to start sending change notifications, so prepare the table view for updates. [self.tableView beginUpdates]; } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { UITableView *tableView = self.tableView; switch(type) { case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeUpdate: [self _configureCell:(TDBadgedCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; break; case NSFetchedResultsChangeMove: if (newIndexPath != nil) { [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; } else { [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade]; } break; } } - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView endUpdates]; } Inside of the _configureCell:atIndexPath: method I have following code: NSFetchRequest *issuesNumberRequest = [NSFetchRequest new]; NSEntityDescription *issueEntity = [NSEntityDescription entityForName:@"Issue" inManagedObjectContext:managedObjectContext]; [issuesNumberRequest setEntity:issueEntity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"projectId == %@", project.projectId]; [issuesNumberRequest setPredicate:predicate]; NSUInteger issuesNumber = [managedObjectContext countForFetchRequest:issuesNumberRequest error:nil]; [issuesNumberRequest release]; I am using the managedObjectContext again. But when I am trying to insert new Project, app crashes with following exception: Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-984.38/UITableView.m:774 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).' Fortunately, I've found a workaround: if I create and use separate NSManagedObjectContext inside of the _configureCell:atIndexPath: method app won't crash! I only want to know, is this behavior correct or not?

    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

  • why eventsMatchingPredicate returns nil?

    - by OneZero
    Here's my code: NSString * calID = [[NSUserDefaults standardUserDefaults] objectForKey:@"calendarIdentifier"]; EKCalendar *cal = [eventStore calendarWithIdentifier:calID]; // If calendar exists if(cal) { // Retrieve all existing events until today NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:[NSDate distantPast] endDate:[NSDate date] calendars:@[cal]]; self.events = [eventStore eventsMatchingPredicate:predicate]; if(self.events==nil) NSLog(@"nil events!"); } The calendarItentifier is the variable that I stored when I created the calendar in my program, so it's not the case I'm adding events on the wrong calendar. However, the code does not work to retrieve past events on the calendar, it simply returns nil to self.events. But I DID add events on the calendar. Can anything tell me if there's anything wrong with the code?

    Read the article

  • iPhone CoreData join

    - by Ken
    Hi guys, long time reader, first time poster. (A link to this schema is located here) http://www.weeshsoft.com/pix/DatabasePic.jpg I'm trying to get all LanguageEntries from a database for a given category.categoryName and languageset.languageSetName e.g. NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"LanguageEntry" inManagedObjectContext:del.managedObjectContext]; [fetchRequest setEntity:entity]; NSString* predicateString = [NSString stringWithFormat:@"Category.categoryName = %@ AND LanguageSet.languageSetName = %@", @"Food", @"English####Spanish"]; fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString]; NSError *error = nil; NSArray* objects = [del.managedObjectContext executeFetchRequest:fetchRequest error:&error]; This always returns 0 objects. If I set the predicate string to match on one relationship (e.g. Category.categoryName = Food or languageSet.languageSetName = English####Spanish) it will return data. This is baffling, can anyone shed some light? -Ken

    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

  • iPhone: Group by month - Core Data

    - by Shaun
    Hi I store dates in a core data entity attribute, I then display the date in the table cells. I want to group all the cells according to months and only display the relevant dates in the correct sections. I'm using sectionNameKeyPath of the NSFetchedResultsController, but I need to only use the month in the date to group. How can I achieve this? Would I need to create a new attribute and store just the month as a string or can I use NSPredicate? Please can anyone let me know if they have done this or give me some examples. Thanks

    Read the article

  • NSPredicates with custom objects

    - by Horatiu Paraschiv
    Hi, I have the following problem and I cannot figure out how to solve it. I have an NSSet which contains Person objects (NSDictionary with 2 keys: name, age). From time to time I get an NSArray of Person objects and I want to add them to my NSSet but I want to filter out the duplicates. I'm thinking I could use NSPredicates but I am reading the documentation and I can't understand how should I format my NSPredicate to filter out my array content based on what I already have in NSSet. So I have an NSSet with 5 custom objects and I get an NSArray with 6 objects but 3 of them already exist in NSSet and I want to filter them out. I understand what I should do with basic objects like Strings, integers, etc but I don't know how to extend this to work with custom more complex objects. I hope I was clear enough with my problem. Any starting point, example or advice is much appreciated. Thank you!

    Read the article

  • [Cocoa] Temporarily disabled NSArrayController filterPredicate, or consult ManagedObjectContext?

    - by ndg
    I have an NSArrayController which is bound to a class in my Managed Object Context. During runtime the NSArrayController can have a number of different filter predicates applied. At certain intervals, I want to iterate through my NSArrayController's contents regardless of the filter predicate applied to it. To do this, I set the filterPredicate to nil and then reinstate it after having iterated through my array. This seems to work, but I'm wondering if it's best practice? Should I instead be polling my Managed Object Context manually? NSPredicate *predicate = nil; predicate = [myArrayController filterPredicate]; [myArrayController setFilterPredicate:nil]; for(MyManagedObject *object in [myArrayController arrangedObjects]) { // ... } [myArrayController setFilterPredicate:predicate];

    Read the article

  • Temporarily disabled NSArrayController filterPredicate, or consult ManagedObjectContext?

    - by ndg
    I have an NSArrayController which is bound to a class in my Managed Object Context. During runtime the NSArrayController can have a number of different filter predicates applied. At certain intervals, I want to iterate through my NSArrayController's contents regardless of the filter predicate applied to it. To do this, I set the filterPredicate to nil and then reinstate it after having iterated through my array. This seems to work, but I'm wondering if it's best practice? Should I instead be polling my Managed Object Context manually? NSPredicate *predicate = nil; predicate = [myArrayController filterPredicate]; [myArrayController setFilterPredicate:nil]; for(MyManagedObject *object in [myArrayController arrangedObjects]) { // ... } [myArrayController setFilterPredicate:predicate];

    Read the article

  • Core Data: Fetch all entities in a to-many-relationship of a particular object?

    - by Björn Marschollek
    Hi there, in my iPhone application I am using simple Core Data Model with two entities (Item and Property): Item name properties Property name value item Item has one attribute (name) and one one-to-many-relationship (properties). Its inverse relationship is item. Property has two attributes the according inverse relationship. Now I want to show my data in table views on two levels. The first one lists all items; when one row is selected, a new UITableViewController is pushed onto my UINavigationController's stack. The new UITableView is supposed to show all properties (i.e. their names) of the selected item. To achieve this, I use a NSFetchedResultsController stored in an instance variable. On the first level, everything works fine when setting up the NSFetchedResultsController like this: -(NSFetchedResultsController *) fetchedResultsController { if (fetchedResultsController) return fetchedResultsController; // goal: tell the FRC to fetch all item objects. NSFetchRequest *fetch = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:self.moContext]; [fetch setEntity:entity]; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; [fetch setSortDescriptors:[NSArray arrayWithObject:sort]]; [fetch setFetchBatchSize:10]; NSFetchedResultsController *frController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetch managedObjectContext:self.moContext sectionNameKeyPath:nil cacheName:@"cache"]; self.fetchedResultsController = frController; fetchedResultsController.delegate = self; [sort release]; [frController release]; [fetch release]; return fetchedResultsController; } However, on the second-level UITableView, I seem to do something wrong. I implemented the fetchedresultsController in a similar way: -(NSFetchedResultsController *) fetchedResultsController { if (fetchedResultsController) return fetchedResultsController; // goal: tell the FRC to fetch all property objects that belong to the previously selected item NSFetchRequest *fetch = [[NSFetchRequest alloc] init]; // fetch all Property entities. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Property" inManagedObjectContext:self.moContext]; [fetch setEntity:entity]; // limit to those entities that belong to the particular item NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"item.name like '%@'",self.item.name]]; [fetch setPredicate:predicate]; // sort it. Boring. NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; [fetch setSortDescriptors:[NSArray arrayWithObject:sort]]; NSError *error = nil; NSLog(@"%d entities found.",[self.moContext countForFetchRequest:fetch error:&error]); // logs "3 entities found."; I added those properties before. See below for my saving "problem". if (error) NSLog("%@",error); // no error, thus nothing logged. [fetch setFetchBatchSize:20]; NSFetchedResultsController *frController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetch managedObjectContext:self.moContext sectionNameKeyPath:nil cacheName:@"cache"]; self.fetchedResultsController = frController; fetchedResultsController.delegate = self; [sort release]; [frController release]; [fetch release]; return fetchedResultsController; } Now it's getting weird. The above NSLog statement returns me the correct number of properties for the selected item. However, the UITableViewDelegate method tells me that there are no properties: -(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; NSLog(@"Found %d properties for item \"%@\". Should have found %d.",[sectionInfo numberOfObjects], self.item.name, [self.item.properties count]); // logs "Found 0 properties for item "item". Should have found 3." return [sectionInfo numberOfObjects]; } The same implementation works fine on the first level. It's getting even weirder. I implemented some kind of UI to add properties. I create a new Property instance via Property *p = [NSEntityDescription insertNewObjectForEntityForName:@"Property" inManagedObjectContext:self.moContext];, set up the relationships and call [self.moContext save:&error]. This seems to work, as error is still nil and the object gets saved (I can see the number of properties when logging the Item instance, see above). However, the delegate methods are not fired. This seems to me due to the possibly messed up fetchRequest(Controller). Any ideas? Did I mess up the second fetch request? Is this the right way to fetch all entities in a to-many-relationship for a particular instance at all?

    Read the article

  • Core Data: Multiple conditions inside relational aggregate operations

    - by Uzaak
    I have an SQLite table used by Core Data with the following elements: Name: John LastName: Foobar Age: 23 Name: Bob LastName: Baz Age: 37 Name: Peter LastName: Fooqux Age: 32 Name: John LastName: Bar Age: 29 Those are all in a to-many relationship from another object "Company". I need to query the database and retrieve all Company objects with employees called "John" but whose last name does NOT contain "Foo". I did go as far as to make the following predicate: [NSPredicate predicateWithFormat:@"ANY employee.name = 'John'"]; How do I get to filter only by companies whose Johns don't have "Foo" in their last names?

    Read the article

  • Why aren't my objects sorting with sortedArrayUsingDescriptors?

    - by clozach
    I expected the code below to return the objects in imageSet as a sorted array. Instead, there's no difference in the ordering before and after. NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"imageID" ascending:YES]; NSSet *imageSet = collection.images; for (CBImage *image in imageSet) { NSLog(@"imageID in Set: %@",image.imageID); } NSArray *imageArray = [[imageSet allObjects] sortedArrayUsingDescriptors:(descriptor, nil)]; [descriptor release]; for (CBImage *image in imageArray) { NSLog(@"imageID in Array: %@",image.imageID); } Fwiw, CBImage is defined in my core data model. I don't know why sorting on managed objects would work any differently than on "regular" objects, but maybe it matters. As proof that @"imageID" should work as the key for the descriptor, here's what the two log loops above output for one of the sets I'm iterating through: 2010-05-05 00:49:52.876 Cover Browser[38678:207] imageID in Array: 360339 2010-05-05 00:49:52.876 Cover Browser[38678:207] imageID in Array: 360337 2010-05-05 00:49:52.877 Cover Browser[38678:207] imageID in Array: 360338 2010-05-05 00:49:52.878 Cover Browser[38678:207] imageID in Array: 360336 2010-05-05 00:49:52.879 Cover Browser[38678:207] imageID in Array: 360335 ... For extra credit, I'd love to get a general solution to troubleshooting NSSortDescriptor troubles (esp. if it also applies to troubleshooting NSPredicate). The functionality of these things seems totally opaque to me and consequently debugging takes forever.

    Read the article

  • UICollectionView with one static cell and N dynamic ones from a fetchresultscontroller exception

    - by nflacco
    I'm trying to make a UITableView that shows a blog post and comments for that post. My setup is a tableview in storyboard with two dynamic prototype cells. The first cell is for the post and should never change. The second cell represents the 0 to N comments. My cellForRowAtIndexPath method shows the post cell properly, but fails to get the comment at the given index path (though if I comment out the fetch I get the appropriate number of comment cells with a green background that I set as a visual debug thing). let comment = fetchedResultController.objectAtIndexPath(indexPath) as Comment I get the following exception on this line: 2014-08-24 15:06:40.712 MessagePosting[21767:3266409] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' *** First throw call stack: ( 0 CoreFoundation 0x0000000101aa43e5 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x00000001037f9967 objc_exception_throw + 45 2 CoreFoundation 0x000000010198f4c3 -[__NSArrayM objectAtIndex:] + 227 3 CoreData 0x00000001016e4792 -[NSFetchedResultsController objectAtIndexPath:] + 162 Section and cell setup: override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. switch section { case 0: return 1 default: if let realPost:Post = post { return fetchedResultController.sections[0].numberOfObjects } else { return 0 } } } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { switch indexPath.section { case 0: let cell = tableView.dequeueReusableCellWithIdentifier(postViewCellIdentifier, forIndexPath: indexPath) as UITableViewCell cell.backgroundColor = lightGrey if let realPost:Post = self.post { cell.textLabel.text = realPost.text } return cell default: let cell = tableView.dequeueReusableCellWithIdentifier(commentCellIdentifier, forIndexPath: indexPath) as UITableViewCell cell.backgroundColor = UIColor.greenColor() let comment = fetchedResultController.objectAtIndexPath(indexPath) as Comment // <---------------------------- :( cell.textLabel.text = comment.text return cell } } FRC: func controllerDidChangeContent(controller: NSFetchedResultsController!) { tableView.reloadData() } func getFetchedResultController() -> NSFetchedResultsController { fetchedResultController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultController } func taskFetchRequest() -> NSFetchRequest { if let realPost:Post = self.post { let fetchRequest = NSFetchRequest(entityName: "Comment") let sortDescriptor = NSSortDescriptor(key: "date", ascending: false) fetchRequest.predicate = NSPredicate(format: "post = %@", realPost) fetchRequest.sortDescriptors = [sortDescriptor] return fetchRequest } else { return NSFetchRequest(entityName: "") } }

    Read the article

  • How to display data stored in core data in a table view?

    - by Dipanjan Dutta
    Hello All, I have developed a core data model for my application. I need to display the saved data into a table view. For my app I have selected split view controller. I am writing down my codes below. Please help me in this regard and write me the code that needs to be added. This is very important as my continuation in my company depends on this. #import "RootViewController.h" #import "DetailViewController.h" #import "AddViewController.h" #import "EmployeeDetailsAppDelegate.h" /* This template does not ensure user interface consistency during editing operations in the table view. You must implement appropriate methods to provide the user experience you require. */ @interface RootViewController () - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath; @end @implementation RootViewController @synthesize detailViewController, fetchedResultsController, managedObjectContext, results, empName; #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { results = [[NSMutableDictionary alloc]init]; [results setObject:empName.text forKey:@"EmployeeName"]; [self.tableView reloadData]; [super viewDidLoad]; } /* - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } */ /* - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ /* - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } */ /* - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape. return YES; } - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = [[managedObject valueForKey:@"EmployeeName"] description]; } #pragma mark - #pragma mark Add a new object - (void)insertNewObject:(id)sender { AddViewController *add = [[AddViewController alloc]initWithNibName:@"AddViewController" bundle:nil]; self.modalPresentationStyle = UIModalPresentationFormSheet; add.wantsFullScreenLayout = NO; [self presentModalViewController:add animated:YES]; [add release]; } #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (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] autorelease]; } // Configure the cell. NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = [[managedObject valueForKey:@"EmployeeName"] description]; return cell; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the managed object. NSManagedObject *objectToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath]; if (self.detailViewController.detailItem == objectToDelete) { self.detailViewController.detailItem = nil; } NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; [context deleteObject:objectToDelete]; NSError *error; if (![context save:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } } - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // The table view should not be re-orderable. return NO; } #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Set the detail item in the detail view controller. NSManagedObject *selectedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; self.detailViewController.detailItem = selectedObject; } #pragma mark - #pragma mark Fetched results controller - (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. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Details" inManagedObjectContext: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:@"EmployeeName" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; [aFetchedResultsController release]; [fetchRequest release]; [sortDescriptor release]; [sortDescriptors release]; return fetchedResultsController; } #pragma mark - #pragma mark Fetched results controller delegate - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { [self.tableView beginUpdates]; } - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { UITableView *tableView = self.tableView; switch(type) { case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeUpdate: [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; break; case NSFetchedResultsChangeMove: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView endUpdates]; } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc. that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)dealloc { [detailViewController release]; [fetchedResultsController release]; [managedObjectContext release]; [super dealloc]; } @end // // AddViewController.m // EmployeeDetails // // Created by Dipanjan on 15/02/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import "AddViewController.h" #import "EmployeeDetailsAppDelegate.h" #import "RootViewController.h" @implementation AddViewController @synthesize empName; @synthesize empID; @synthesize empDepartment; @synthesize backButton; // 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 { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization. } return self; } */ /* // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; } */ -(void)saveDetails{ EmployeeDetailsAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSManagedObject *newDetails; newDetails = [NSEntityDescription insertNewObjectForEntityForName:@"Details" inManagedObjectContext:context]; [newDetails setValue:empID.text forKey:@"EmployeeID"]; [newDetails setValue:empName.text forKey:@"EmployeeName"]; [newDetails setValue:empDepartment.text forKey:@"EmployeeDepartment"]; empID.text = @""; empName.text = @""; empDepartment.text = @""; NSLog(@"%@........----->>>...", newDetails); NSError *error; [context save:&error]; [self dismissModalViewControllerAnimated:YES]; } -(void)findDetails { EmployeeDetailsAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Details" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc]init]; [request setEntity:entityDesc]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"(EmployeeName = %@)", empName.text]; [request setPredicate:pred]; NSManagedObject *matches = nil; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error]; if ([objects count] == 0) { } else { matches = [objects objectAtIndex:0]; empID.text = [matches valueForKey:@"EmployeeID"]; empDepartment.text = [matches valueForKey:@"EmployeeDepartment"]; } [request release]; [self dismissModalViewControllerAnimated:YES]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Overriden to allow any orientation. return YES; } - (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 { self.empName = nil; self.empID = nil; self.empDepartment = nil; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [empID release]; [empName release]; [empDepartment release]; [super dealloc]; } @end Please let me know the answer as soon as possible. Thank you. Regards, Dipanjan

    Read the article

  • Core Data: migrating entities with self-referential properties

    - by Dan
    My Core Data model contains an entity, Shape, that has two self-referential relationships, which means four properties. One pair is a one-to-many relationship (Shape.containedBy <- Shape.contains) and the another is a many-to-many relationship (Shape.nextShapes <<- Shape.previousShapes). It all works perfectly in the application, so I don't think self-referencing relationships is a problem in general. However, when it comes to migrating the model to a new version, then Xcode fails to compile the automatically generated mapping model, with this error message: 2009-10-30 17:10:09.387 mapc[18619:607] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "FUNCTION($manager ,'destinationInstancesForSourceRelationshipNamed:sourceInstances:' , 'contains' , $source.contains) == 1"' *** Call stack at first throw: ( 0 CoreFoundation 0x00007fff80d735a4 __exceptionPreprocess + 180 1 libobjc.A.dylib 0x00007fff83f0a313 objc_exception_throw + 45 2 Foundation 0x00007fff819bc8d4 _qfqp2_performParsing + 8412 3 Foundation 0x00007fff819ba79d +[NSPredicate predicateWithFormat:arguments:] + 59 4 Foundation 0x00007fff81a482ef +[NSExpression expressionWithFormat:arguments:] + 68 5 Foundation 0x00007fff81a48843 +[NSExpression expressionWithFormat:] + 155 6 XDBase 0x0000000100038e94 -[XDDevRelationshipMapping valueExpressionAsString] + 260 7 XDBase 0x000000010003ae5c -[XDMappingCompilerSupport generateCompileResultForMappingModel:] + 2828 8 XDBase 0x000000010003b135 -[XDMappingCompilerSupport compileSourcePath:options:] + 309 9 mapc 0x0000000100001a1c 0x0 + 4294973980 10 mapc 0x0000000100001794 0x0 + 4294973332 ) terminate called after throwing an instance of 'NSException' Command /Developer/usr/bin/mapc failed with exit code 6 The 'contains' is the name of one of the self-referential properties. Anyway, the really big problem is that I can't even look at this Mapping Property as Xcode crashes as soon as I select the entity mapping when viewing the mapping model. So I'm a bit lost really where to go from here. I really can't remove the self-referential properties, so I'm thinking I've got manually create a mapping model that compiles? Any ideas? Cheers

    Read the article

  • Return a Const Char* by reading an @property NSString in separate class

    - by Andrew
    I'm probably being an idiot here, but I cannot for the life of me find the answer that I'm looking for. I have an array of CalEvents returned from a CalendarStore query, and for other reasons I am finding the first location of any upcoming event for today that is not an all-day or multi-day event. +(const char*) suggestFirstiCalLocation{ CalCalendarStore *store = [CalCalendarStore defaultCalendarStore]; NSPredicate *allEventsPredicate = [CalCalendarStore eventPredicateWithStartDate:[NSDate date] endDate:[[NSDate date] initWithTimeIntervalSinceNow:3600] calendars:[store calendars]]; NSArray *currentEventCalendarArray = [store eventsWithPredicate:allEventsPredicate]; for (int i = 0; i< [currentEventCalendarArray count]; i++){ if (![[currentEventCalendarArray objectAtIndex:i] isAllDay]){ //Now that other events are cleared, check for multi-day NSDate *startOnDate = [[currentEventCalendarArray objectAtIndex:i] startDate]; NSDate *endOnDate = [[currentEventCalendarArray objectAtIndex:i] endDate]; if ([endOnDate timeIntervalSinceDate:startOnDate ] < 86400.0){ NSString * iCalLocation = [[currentEventCalendarArray objectAtIndex:i] location]; return [iCalLocation UTF8String]; } } } return ""; } For other reasons, I am returning a const char with the value of the location that is found. However, I cannot seem to return "iCalLocation" at all. The compiler fails on the line where I am initializing the "iCalLocation" variable: "Cannot convert to pointer type" Being frank: I am new to Objective-C, and I am still trying to figure points, properties, and such out.

    Read the article

  • iPhone - sorting the results of a core data entity

    - by Digital Robot
    I have a core data entity that represents the attributes of a product, as number, price, etc. The product number is a NSString property and follows the form X.y where X is a number variable of digits and Y is one digit. For example. 132.2, 99.4, etc. I am querying the database to obtain the list of product numbers in order: The code is like this: + (NSArray*)todosOsItens:(NSString *)pName inManagedObjectContext:(NSManagedObjectContext *)context { Product *aProduct = [Product productWithName:pName inManagedObjectContext:context]; NSArray *all = nil; NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.entity = [NSEntityDescription entityForName:@"Attributes" inManagedObjectContext:context]; request.predicate = [NSPredicate predicateWithFormat: @"(belongsTo == %@)", aProduct]; [request setResultType:NSDictionaryResultType]; [request setReturnsDistinctResults:YES]; [request setPropertiesToFetch:[NSArray arrayWithObject:item]]; NSSortDescriptor *sortByItem = [NSSortDescriptor sortDescriptorWithKey:@"ProductNumber" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortByItem]; [request setSortDescriptors:sortDescriptors]; NSError *error = nil; all = [[context executeFetchRequest:request error:&error] mutableCopy]; [request release]; return all; } but this query is not returning the sorted results. The results are coming on their natural order on the database. How do I do that? thanks.

    Read the article

  • How to optimize Core Data query for full text search

    - by dk
    Can I optimize a Core Data query when searching for matching words in a text? (This question also pertains to the wisdom of custom SQL versus Core Data on an iPhone.) I'm working on a new (iPhone) app that is a handheld reference tool for a scientific database. The main interface is a standard searchable table view and I want as-you-type response as the user types new words. Words matches must be prefixes of words in the text. The text is composed of 100,000s of words. In my prototype I coded SQL directly. I created a separate "words" table containing every word in the text fields of the main entity. I indexed words and performed searches along the lines of SELECT id, * FROM textTable JOIN (SELECT DISTINCT textTableId FROM words WHERE word BETWEEN 'foo' AND 'fooz' ) ON id=textTableId LIMIT 50 This runs very fast. Using an IN would probably work just as well, i.e. SELECT * FROM textTable WHERE id IN (SELECT textTableId FROM words WHERE word BETWEEN 'foo' AND 'fooz' ) LIMIT 50 The LIMIT is crucial and allows me to display results quickly. I notify the user that there are too many to display if the limit is reached. This is kludgy. I've spent the last several days pondering the advantages of moving to Core Data, but I worry about the lack of control in the schema, indexing, and querying for an important query. Theoretically an NSPredicate of textField MATCHES '.*\bfoo.*' would just work, but I'm sure it will be slow. This sort of text search seems so common that I wonder what is the usual attack? Would you create a words entity as I did above and use a predicate of "word BEGINSWITH 'foo'"? Will that work as fast as my prototype? Will Core Data automatically create the right indexes? I can't find any explicit means of advising the persistent store about indexes. I see some nice advantages of Core Data in my iPhone app. The faulting and other memory considerations allow for efficient database retrievals for tableview queries without setting arbitrary limits. The object graph management allows me to easily traverse entities without writing lots of SQL. Migration features will be nice in the future. On the other hand, in a limited resource environment (iPhone) I worry that an automatically generated database will be bloated with metadata, unnecessary inverse relationships, inefficient attribute datatypes, etc. Should I dive in or proceed with caution?

    Read the article

  • Cocoa's newbie question: is it possible to bind a NSTableView's selection to another tableview's selection?

    - by cocoaOverloaded
    http://img651.imageshack.us/img651/6999/modelsf.jpg Let'say, I've 2 entities in the Core Data's Model file, one being all "transactions" ever done by X company. The "transactions" entity has among other properties, a "DATE" property and a to-one relationship "COMPANY"(specifying the company with which X company has done that particular transaction). The other entity:"companies" of course contains all the companies' info ,with which X company has done transaction. The "companies" entity has a to-many relationships "TRANSACTIONS" which is an inverse relationship to "transactions" entity's "COMPANY" relationship. So within IB, I created a NSTableView(with its own NSArrayController) showing all the transactions on a particular Date (with the help of NSPredicate). Then I create another table view showing the to-many relationship "TRANSACTIONS" of the company of the selected transaction in the first table view(which shows transactions on a particular date). The 2nd table view's NSArrayController binding is like this: ** bind to: "name of the first tableview's controller", Controller Key: selection, Model Key Path:COMPANY.TRANSACTIONS(the to-many relationship in the "companies" entity)** Everythings work fine up to this moment, the 2nd tableview shows all the transactions X company has done with the company of the selected transactions in the 1st table view. But I have a group of textfields showing details of a particular transactions. Binding the these textfields with the controller of the 1st table view(the one showing transactions on a particular date) is pretty straightforward. But what I want to do are: 1/ Look up the transactions on a particular date in the first table view, select any one of them 2/ Then, check all previous transactions of the company of that transaction( selected in the first table view) from the 2nd table view 3/ Select any previous transactions and check the details of the transaction from that group of textfields So naturally I should have bind the textfields' gp to the 2nd table view's controller. But I found the default selected row in the 2nd table view(the one show all previous transactions of a company) wasn't the transaction I've selected in the 1st tableView for a particular date. Of course, i can manually select that transaction in the 2nd table view again.... So I just want to know if it's possible to have the 2nd table view automatically select the transaction according to the transaction I've selected in the 1st table view thr binding?? After hours of googling, I solved the problem by implementing the tableview Delegate protocol: - (void)tableViewSelectionDidChange:(NSNotification *)aNotification { if (["nameOf1stTableView" selectedRow] > -1) { NSArray *objsArray = ["nameOf2ndTableView'sController" arrangedObjects]; for (id obj in objsArray) { if ([[obj valueForKey:@"DATE"] isEqualToDate: ["nameOf1stTableView'sController".selection valueForKey:@"DATE"]]) { ["nameOf2ndTableView" selectRowIndexes:[NSIndexSet indexSetWithIndex:[objsArray indexOfObject:obj]] byExtendingSelection:NO]; } } } } But,this just look too cumbersome... can it be done with binding alone? Thanks in Advance,

    Read the article

  • inserting new relationship data in core-data

    - by michael
    My app will allow users to create a personalised list of events from a large list of events. I have a table view which simply displays these events, tapping on one of them takes the user to the event details view, which has a button "add to my events". In this detailed view I own the original event object, retrieved via an NSFetchedResultsController and passed to the detailed view (via a table cell, the same as the core data recipes sample). I have no trouble retrieving/displaying information from this "event". I am then trying to add it to the list of MyEvents represented by a one to many (inverse) relationship: This code: NSManagedObjectContext *context = [event managedObjectContext]; MyEvents *myEvents = (MyEvents *)[NSEntityDescription insertNewObjectForEntityForName:@"MyEvents" inManagedObjectContext:context]; [myEvents addEventObject:event];//ERROR And this code (suggested below): //would this add to or overwrite the "list" i am attempting to maintain NSManagedObjectContext *context = [event managedObjectContext]; MyEvents *myEvents = (MyEvents *)[NSEntityDescription insertNewObjectForEntityForName:@"MyEvents" inManagedObjectContext:context]; NSMutableSet *myEvent = [myEvents mutableSetValueForKey:@"event"]; [myEvent addObject:event]; //ERROR Bot produce (at the line indicated by //ERROR): *** -[NSComparisonPredicate evaluateWithObject:]: message sent to deallocated instance Seems I may have missed something fundamental. I cant glean any more information through the use of debugging tools, with my knowledge of them. 1) Is this a valid way to compile and store an editable list like this? 2) Is there a better way? 3) What could possibly be the deallocated instance in error? -- I have now modified the Event entity to have a to-many relationship called "myEvents" which referrers to itself. I can add Events to this fine, and logging the object shows the correct memory addresses appearing for the relationship after a [event addMyEventObject:event];. The same failure happens right after this however. I am still at a loss to understand what is going wrong. This is the backtrace #0 0x01f753a7 in ___forwarding___ () #1 0x01f516c2 in __forwarding_prep_0___ () #2 0x01c5aa8f in -[NSFetchedResultsController(PrivateMethods) _preprocessUpdatedObjects:insertsInfo:deletesInfo:updatesInfo:sectionsWithDeletes:newSectionNames:treatAsRefreshes:] () #3 0x01c5d63b in -[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] () #4 0x0002e63a in _nsnote_callback () #5 0x01f40005 in _CFXNotificationPostNotification () #6 0x0002bef0 in -[NSNotificationCenter postNotificationName:object:userInfo:] () #7 0x01bbe17d in -[NSManagedObjectContext(_NSInternalNotificationHandling) _postObjectsDidChangeNotificationWithUserInfo:] () #8 0x01c1d763 in -[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:withDeletions:withUpdates:withRefreshes:] () #9 0x01ba25ea in -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] () #10 0x01bdfb3a in -[NSManagedObjectContext processPendingChanges] () #11 0x01bd0957 in _performRunLoopAction () #12 0x01f4d252 in __CFRunLoopDoObservers () #13 0x01f4c65f in CFRunLoopRunSpecific () #14 0x01f4bc48 in CFRunLoopRunInMode () #15 0x0273878d in GSEventRunModal () #16 0x02738852 in GSEventRun () #17 0x002ba003 in UIApplicationMain () solution I managed to get to the bottom of this. I was fetching the event in question using a NSFetchedResultsController with a NSPredicate which I was releasing after I had the results. Retrieving values from the entities returned was no problem, but when I tried to update any of them it gave the error above. It should not have been released. oustanding part of my question What is a good way to create this sub list from a list of existing items in terms of a core data model. I don't believe its any of the ways I tried here. I need to show/edit it in another table view. Perhaps there is a better way than a boolean property on each event entity? The relationship idea above doesn't seem to work here (even though I can now create it). Cheers.

    Read the article

  • EKCalendar not added to iCal

    - by Alex75
    I have a strange behavior on my iPhone. I'm creating an application that uses calendar events (EventKit). The class that use is as follows: the .h one #import "GenericManager.h" #import <EventKit/EventKit.h> #define oneDay 60*60*24 #define oneHour 60*60 @protocol CalendarManagerDelegate; @interface CalendarManager : GenericManager /* * metodo che aggiunge un evento ad un calendario di nome Name nel giorno onDate. * L'evento da aggiungere viene recuperato tramite il dataSource che è quindi * OBBLIGATORIO (!= nil). * * Restituisce YES solo se il delegate è conforme al protocollo CalendarManagerDataSource. * NO altrimenti */ + (BOOL) addEventForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate; /* * metodo che aggiunge un evento per giorno compreso tra fromDate e toDate ad un * calendario di nome Name. L'evento da aggiungere viene recuperato tramite il dataSource * che è quindi OBBLIGATORIO (!= nil). * * Restituisce YES solo se il delegate è conforme al protocollo CalendarManagerDataSource. * NO altrimenti */ + (BOOL) addEventsForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate; @end @protocol CalendarManagerDelegate <NSObject> // viene inviato quando il calendario necessita informazioni sull' evento da aggiungere - (void) calendarManagerDidCreateEvent:(EKEvent *) event; @end the .m one // // CalendarManager.m // AppCampeggioSingolo // // Created by CreatiWeb Srl on 12/17/12. // Copyright (c) 2012 CreatiWeb Srl. All rights reserved. // #import "CalendarManager.h" #import "Commons.h" #import <objc/message.h> @interface CalendarManager () @end @implementation CalendarManager + (void)requestToEventStore:(EKEventStore *)eventStore delegate:(id)delegate fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate name:(NSString *)name { if([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { // ios >= 6.0 [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (granted) { [self addEventForCalendarWithName:name fromDate: fromDate toDate: toDate inEventStore:eventStore withDelegate:delegate]; } else { } }]; } else if (class_getClassMethod([EKCalendar class], @selector(calendarIdentifier)) != nil) { // ios >= 5.0 && ios < 6.0 [self addEventForCalendarWithName:name fromDate:fromDate toDate:toDate inEventStore:eventStore withDelegate:delegate]; } else { // ios < 5.0 EKCalendar *myCalendar = [eventStore defaultCalendarForNewEvents]; EKEvent *event = [self generateEventForCalendar:myCalendar fromDate: fromDate toDate: toDate inEventStore:eventStore withDelegate:delegate]; [eventStore saveEvent:event span:EKSpanThisEvent error:nil]; } } /* * metodo che recupera l'identificativo del calendario associato all'app o nil se non è mai stato creato. */ + (NSString *) identifierForCalendarName: (NSString *) name { NSString * confFileName = [self pathForFile:kCurrentCalendarFileName]; NSDictionary *confCalendar = [NSDictionary dictionaryWithContentsOfFile:confFileName]; NSString *currentIdentifier = [confCalendar objectForKey:name]; return currentIdentifier; } /* * memorizza l'identifier del calendario */ + (void) saveCalendarIdentifier:(NSString *) identifier andName: (NSString *) name { if (identifier != nil) { NSString * confFileName = [self pathForFile:kCurrentCalendarFileName]; NSMutableDictionary *confCalendar = [NSMutableDictionary dictionaryWithContentsOfFile:confFileName]; if (confCalendar == nil) { confCalendar = [NSMutableDictionary dictionaryWithCapacity:1]; } [confCalendar setObject:identifier forKey:name]; [confCalendar writeToFile:confFileName atomically:YES]; } } + (EKCalendar *)getCalendarWithName:(NSString *)name inEventStore:(EKEventStore *)eventStore withLocalSource: (EKSource *)localSource forceCreation:(BOOL) force { EKCalendar *myCalendar; NSString *identifier = [self identifierForCalendarName:name]; if (force || identifier == nil) { NSLog(@"create new calendar"); if (class_getClassMethod([EKCalendar class], @selector(calendarForEntityType:eventStore:)) != nil) { // da ios 6.0 in avanti myCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore]; } else { myCalendar = [EKCalendar calendarWithEventStore:eventStore]; } myCalendar.title = name; myCalendar.source = localSource; NSError *error = nil; BOOL result = [eventStore saveCalendar:myCalendar commit:YES error:&error]; if (result) { NSLog(@"Saved calendar %@ to event store. %@",myCalendar,eventStore); } else { NSLog(@"Error saving calendar: %@.", error); } [self saveCalendarIdentifier:myCalendar.calendarIdentifier andName:name]; } // You can also configure properties like the calendar color etc. The important part is to store the identifier for later use. On the other hand if you already have the identifier, you can just fetch the calendar: else { myCalendar = [eventStore calendarWithIdentifier:identifier]; NSLog(@"fetch an old-one = %@",myCalendar); } return myCalendar; } + (EKCalendar *)addEventForCalendarWithName: (NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate inEventStore:(EKEventStore *)eventStore withDelegate: (id<CalendarManagerDelegate>) delegate { // da ios 5.0 in avanti EKCalendar *myCalendar; EKSource *localSource = nil; for (EKSource *source in eventStore.sources) { if (source.sourceType == EKSourceTypeLocal) { localSource = source; break; } } @synchronized(self) { myCalendar = [self getCalendarWithName:name inEventStore:eventStore withLocalSource:localSource forceCreation:NO]; if (myCalendar == nil) myCalendar = [self getCalendarWithName:name inEventStore:eventStore withLocalSource:localSource forceCreation:YES]; NSLog(@"End synchronized block %@",myCalendar); } EKEvent *event = [self generateEventForCalendar:myCalendar fromDate:fromDate toDate:toDate inEventStore:eventStore withDelegate:delegate]; [eventStore saveEvent:event span:EKSpanThisEvent error:nil]; return myCalendar; } + (EKEvent *) generateEventForCalendar: (EKCalendar *) calendar fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate inEventStore:(EKEventStore *) eventStore withDelegate:(id<CalendarManagerDelegate>) delegate { EKEvent *event = [EKEvent eventWithEventStore:eventStore]; event.startDate=fromDate; event.endDate=toDate; [delegate calendarManagerDidCreateEvent:event]; [event setCalendar:calendar]; // ricerca dell'evento nel calendario, se ne trovo uno uguale non lo inserisco NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:fromDate endDate:toDate calendars:[NSArray arrayWithObject:calendar]]; NSArray *matchEvents = [eventStore eventsMatchingPredicate:predicate]; if ([matchEvents count] > 0) { // ne ho trovati di gia' presenti, vediamo se uno e' quello che vogliamo inserire BOOL found = NO; for (EKEvent *fetchEvent in matchEvents) { if ([fetchEvent.title isEqualToString:event.title] && [fetchEvent.notes isEqualToString:event.notes]) { found = YES; break; } } if (found) { // esiste già e quindi non lo inserisco NSLog(@"OH NOOOOOO!!"); event = nil; } } return event; } #pragma mark - Public Methods + (BOOL) addEventForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate { BOOL retVal = YES; EKEventStore *eventStore=[[EKEventStore alloc] init]; if ([delegate conformsToProtocol:@protocol(CalendarManagerDelegate)]) { [self requestToEventStore:eventStore delegate:delegate fromDate:fromDate toDate: toDate name:name]; } else { retVal = NO; } return retVal; } + (BOOL) addEventsForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate { BOOL retVal = YES; NSDate *dateCursor = fromDate; EKEventStore *eventStore=[[EKEventStore alloc] init]; if ([delegate conformsToProtocol:@protocol(CalendarManagerDelegate)]) { while (retVal && ([dateCursor compare:toDate] == NSOrderedAscending)) { NSDate *finish = [dateCursor dateByAddingTimeInterval:oneDay]; [self requestToEventStore:eventStore delegate:delegate fromDate: dateCursor toDate: finish name:name]; dateCursor = [dateCursor dateByAddingTimeInterval:oneDay]; } } else { retVal = NO; } return retVal; } @end In practice, on my iphone I get the log: fetch an old-one = (null) 19/12/2012 11:33:09.520 AppCampeggioSingolo [730:8 b1b] create new calendar 19/12/2012 11:33:09.558 AppCampeggioSingolo [730:8 b1b] Saved calendar EKCalendar every time I add an event, then I look and I can not find it on iCal calendar event he added. On the iPhone of a friend of mine, however, everything is working correctly. I doubt that the problem stems from the code, but just do not understand what it could be. I searched all day yesterday and part of today on google but have not found anything yet. Any help will be greatly appreciated EDIT: I forgot the call wich is [CalendarManager addEventForCalendarWithName: @"myCalendar" fromDate:fromDate toDate: toDate withDelegate:self]; in the delegate method simply set title and notes of the event like this - (void) calendarManagerDidCreateEvent:(EKEvent *) event { event.title = @"the title"; event.notes = @"some notes"; }

    Read the article

< Previous Page | 1 2 3 4 5