Search Results

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

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

  • Objective-C: fetchManagedObjectsForEntity problem

    - by Meko
    Hi.I am trying to get value from CoreData entity name Person with predicate and then comparing with new data in dictionary.But it it returns every time 0 .And it creates about 5 person with same name. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName == %@",[flickr usernameForUserID:@"owner"]]; peopleList = (NSMutableArray *)[flickr fetchManagedObjectsForEntity:@"Person" withPredicate:predicate]; NSEnumerator *enumerator = [peopleList objectEnumerator]; Person *person; BOOL exists = FALSE; while (person = [enumerator nextObject]) { NSLog(@" Person is: %@ ", person.userName); NSLog(@"Person ID IS %@",person.userID); NSLog(@"Dict ID is %@",[dict objectForKey:@"owner"]); if([person.userID isEqualToString:[dict objectForKey:@"owner"]]) { exists = TRUE; NSLog(@"-- Person Exists : %@--", person.userName); [newPhoto setPerson:person]; } } Here peopleList returns 0 and the enumerator also 0 and it does not use if and not comparing.In my entity I have Person and Photo entities.In Person I have userName and userID attributes and also one-to many relationship with Photo entity. I think problem in predicate but i cant figure out it .

    Read the article

  • Core Data Relationship problem

    - by awattar
    I have a very simple model with two objects: Name and Category. One Name can be in many Categories (it's one way relationship). I'm trying to create 8 Categories every with 8 Names. Example code: NSMutableArray *localArray = [NSMutableArray arrayWithObjects: [NSMutableDictionary dictionaryWithObjectsAndKeys: @"g1", @"Name", @"g1", @"Icon", [NSNumber numberWithBool:YES] , @"Male", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"g2", @"Name", @"g2", @"Icon", [NSNumber numberWithBool:YES] , @"Male", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"g3", @"Name", @"g3", @"Icon", [NSNumber numberWithBool:YES] , @"Male", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"g4", @"Name", @"g4", @"Icon", [NSNumber numberWithBool:YES] , @"Male", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"g5", @"Name", @"g5", @"Icon", [NSNumber numberWithBool:YES] , @"Male", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"g6", @"Name", @"g6", @"Icon", [NSNumber numberWithBool:YES] , @"Male", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"g7", @"Name", @"g7", @"Icon", [NSNumber numberWithBool:YES] , @"Male", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"g8", @"Name", @"g8", @"Icon", [NSNumber numberWithBool:YES] , @"Male", nil], nil]; NSMutableArray *localArray2 = [NSMutableArray arrayWithObjects: [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test1", @"Name", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test2", @"Name", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test3", @"Name", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test4", @"Name", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test5", @"Name", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test6", @"Name", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test7", @"Name", nil], [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test8", @"Name", nil], nil]; NSError *error; NSManagedObjectContext *moc = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; for(NSMutableDictionary *item in localArray) { NSManagedObject *category = [NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:managedObjectContext]; [category setValue:[item objectForKey:@"Name"] forKey:@"Name"]; [category setValue:[item objectForKey:@"Icon"] forKey:@"Icon"]; [category setValue:[item objectForKey:@"Male"] forKey:@"Male"]; for(NSMutableDictionary *item2 in localArray2) { NSManagedObject *name = [NSEntityDescription insertNewObjectForEntityForName:@"Name" inManagedObjectContext:managedObjectContext]; [name setValue:[item2 objectForKey:@"Name"] forKey:@"Name"]; [[name mutableSetValueForKey:@"CategoryRelationship"] addObject:category]; } } [moc save:&error]; And here's a problem - i've checked that 8 Categories are saved, 64 Names are saved but only 8 from all Names are connected with any category. So when i query for Names in Categories [NSPredicate predicateWithFormat:@"CategoryRelationship.@count != 0"] there are 8 elements and when [NSPredicate predicateWithFormat:@"CategoryRelationship.@count = 0"] there are 56 elements. What is going one here?

    Read the article

  • Simple CalendarStore query puts application into infinite loop!?

    - by Frank R.
    Hi, I've been looking at adding iCal support to my new application and everything seemed just fine and worked on my Mac OS X 10.6 Snow Leopard development machine without a hitch. Now it looks like depending on what is in your calendar the very simple query below: - (NSArray*) fetchCalendarEventsForNext50Minutes { NSLog(@"fetchCalendarEventsForNext50Minutes"); NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate]; NSDate* startDate = [[NSDate alloc] init]; NSDate* endDate = [startDate addTimeInterval: 50.0 * 60.0]; NSPredicate *eventsForTheNext50Minutes = [CalCalendarStore eventPredicateWithStartDate:startDate endDate:endDate calendars:[[CalCalendarStore defaultCalendarStore] calendars]]; // Fetch all events for this year NSArray *events = [[CalCalendarStore defaultCalendarStore] eventsWithPredicate: eventsForTheNext50Minutes]; NSLog( @"fetch took: %f seconds", [NSDate timeIntervalSinceReferenceDate] - start ); return events; } produces a beachball thrash even with quite limited events in the calendar store. Am I missing something crucial here? The code snippet is pretty much exactly from the documentation at: // Create a predicate to fetch all events for this year NSInteger year = [[NSCalendarDate date] yearOfCommonEra]; NSDate *startDate = [[NSCalendarDate dateWithYear:year month:1 day:1 hour:0 minute:0 second:0 timeZone:nil] retain]; NSDate *endDate = [[NSCalendarDate dateWithYear:year month:12 day:31 hour:23 minute:59 second:59 timeZone:nil] retain]; NSPredicate *eventsForThisYear = [CalCalendarStore eventPredicateWithStartDate:startDate endDate:endDate calendars:[[CalCalendarStore defaultCalendarStore] calendars]]; // Fetch all events for this year NSArray *events = [[CalCalendarStore defaultCalendarStore] eventsWithPredicate:eventsForThisYear]; It looks like it has something to do with the recurrence rules, but as far as I can see there are no other ways of fetching events from the calendar store anyway. Has anybody else come across this? Best regards, Frank

    Read the article

  • Core data setReturnsDistinctResult not working

    - by Moze
    So i'm building a small application, it uses core data database of ~25mb size with 4 entities. It's for bus timetables. In one table named "Stop" there are have ~1300 entries of bus stops with atributes "name", "id", "longitude", "latitude" and couple relationships. Now there are many stops with same name but different coordinates and id. Search is implemented using NSPredicate. So I want to show all distinct stop names in table view, i'm using setReturnsDistinctResults with NSDictionaryResultType and setPropertiesToFetch. But setReturnsDistinctResult is not working and I'm still getting all entries. Heres code: - (NSFetchRequest *)fetchRequest { if (fetchRequest == nil) { fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Stop" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSArray *sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease]]; [fetchRequest setSortDescriptors:sortDescriptors]; [fetchRequest setResultType:NSDictionaryResultType]; [fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"name"]]]; [fetchRequest setReturnsDistinctResults:YES]; DebugLog(@"fetchRequest initialized"); } return fetchRequest; } ///////////////////// - (NSFetchedResultsController *)fetchedResultsController { if (self.predicateString != nil) { self.predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", self.predicateString]; [self.fetchRequest setPredicate:predicate]; } else { self.predicate = nil; [self.fetchRequest setPredicate:predicate]; } fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:self.fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:sectionNameKeyPath cacheName:nil]; return fetchedResultsController; } ////////////// - (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } cell.textLabel.text = [[fetchedResultsController objectAtIndexPath:indexPath] valueForKey:@"name"]; return cell; }

    Read the article

  • Help creating a predicate for use with filteredArrayUsingPredicate

    - by johnbdh
    I am trying to learn how to use predicates and so am trying to replace the following working code with filteredArrayUsingPredicate... [filteredLocations removeAllObjects]; for (NSString *location in locations) { NSRange range = [location rangeOfString:query options:NSCaseInsensitiveSearch]; if (range.length > 0) { [filteredLocations addObject:location]; } } Instead I am trying.... [filteredLocations removeAllObjects]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains %@", searchText]; [filteredLocations addObjectsFromArray: [locations filteredArrayUsingPredicate:predicate]]; I am not getting the same results with the predicate as I am with for loop rangeOfString. With the range of string for example searchText returns an 8 item array while with the same value returns only 2 with the predicate. Another example, hono will find honolulu in the locations array while it will not find anything using the predicate. As I understand it SELF represents the object object being evaluated ie. the locations array, so I think that is the correct syntax. Any help would be appreciated Thanks, John

    Read the article

  • Update a tableView with a plist took from another table

    - by Pheel
    Background: I have a tab bar application, which has a tableView as the "heart" of the app. It loads data from a plist and, through a button that checks if there are any updates on the remote plist file, updates the local plist with the remote contents. Then, i have another tableView, that should display only those plist items that have a bool value set to YES. Now i want to add a button to the second table that reloads the plist took from the first table. Expected: When i update the local plist from the first table and when i press the button on the second table, the 2nd table is supposed to update and show the cells with that bool value set to YES. (Note: I set YES as default to some items on plist). What happens: The first table updates its content from remote. The second table shows the old items with the value set to YES. When i press the button to refresh data, it reads the plist fine (by logging it, it has the same contents of the first table -only those set to YES-),but it doesn't update data even if i have [self.tableView reloadData];. When i close the app and open it again, the second table is filled with the right items. :\ Code i'm using: //Reading Plist { NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *plistPath = [[documentPaths lastObject] stringByAppendingPathComponent:@"myPlist.plist"]; NSFileManager *fMgr = [NSFileManager defaultManager]; if (![fMgr fileExistsAtPath:plistPath]) { plistPath = [[NSBundle mainBundle] pathForResource:@"myPlist" ofType:@"plist"]; } NSMutableArray *returnArr = [NSMutableArray arrayWithContentsOfFile:plistPath]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isFav == YES"]; for (NSDictionary *sect in returnArr) { NSArray *arr = [sect objectForKey:@"Rows"]; [sect setValue:[arr filteredArrayUsingPredicate:predicate] forKey:@"Rows"]; } [self.tableView reloadData]; } //Refresh data button - (void) refreshTable:(id)sender { NSLog(@"plist read"); [self readPlist]; NSLog(@"refreshed plist:%@",[self readPlist]); [self.tableView reloadData]; } Does anyone know why the table is not updating?

    Read the article

  • iPhone NSCFString leaks in fetchRequest

    - by camilo
    In the following code: - (NSMutableArray *) fetchNotesForGroup: (NSString *)groupName { // Variables declaration NSMutableArray *result; NSFetchRequest *fetchRequest; NSEntityDescription *entity; NSSortDescriptor *sortDescriptor; NSPredicate *searchPredicate; NSError *error = nil; // Creates the fetchRequest and executes it fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; entity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"noteName" ascending:YES] autorelease]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; [fetchRequest setReturnsDistinctResults:YES]; searchPredicate = [NSPredicate predicateWithFormat:@"categoryName like %@", groupName]; [fetchRequest setPredicate:searchPredicate]; [fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:@"noteName"]]; result = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy]; // Variables release return result; } ... I Fetch notes for a given categoryName. When I'm running Instruments, it says that a NSCFString is leaking. I know leaks are mean for iPhone developers... but I don't have any idea on how to plug this one. Any clues? All help is welcome. Thanks a lot!

    Read the article

  • Batch faulting in a to-many relationship for a collection of objects

    - by indragie
    Scenario: Let's say I have an entity called Author that has a to-many relationship called books to the Book entity (inverse relationship author). If I have an existing collection of Author objects, I want to fault in the books relationship for all of them in a single fetch request. Code This is what I've tried so far: NSArray *authors = ... // array of `Author` objects NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Book"]; fetchRequest.returnsObjectsAsFaults = NO; fetchRequest.predicate = [NSPredicate predicateWithFormat:@"author IN %@", authors]; Executing this fetch request does not result in the books relationship of the objects in the authors array being faulted in (inspected via logging). I've also tried doing the fetch request the other way around: NSArray *authors = ... // array of `Author` objects NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Author"]; fetchRequest.returnsObjectsAsFaults = NO; fetchRequest.predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", authors]; fetchRequest.relationshipKeypathsForPrefetching = @[@"books"]; This doesn't fire the faults either. What's the appropriate way of going about doing this?

    Read the article

  • What changes in Core Data after a save?

    - by Splash6
    I have a Core Data based mac application that is working perfectly well until I save a file. When I save a file it seems like something changes in core data because my original fetch request no longer fetches anything. This is the fetch request that works before saving but returns an empty array after saving. NSEntityDescription *outputCellEntityDescription = [NSEntityDescription entityForName:@"OutputCell" inManagedObjectContext:[[self document] managedObjectContext]]; NSFetchRequest *outputCellRequest = [[[NSFetchRequest alloc] init] autorelease]; [outputCellRequest setEntity:outputCellEntityDescription]; NSPredicate *outputCellPredicate = [NSPredicate predicateWithFormat:@"(cellTitle = %@)", outputCellTitle]; [outputCellRequest setPredicate:outputCellPredicate]; NSError *outputCellError = nil; NSArray *outputCellArray = [[[self document] managedObjectContext] executeFetchRequest:outputCellRequest error:&outputCellError]; I have checked with [[[self document] managedObjectContext] registeredObjects] to see that the object still exists after the save and nothing seems to have changed and the object still exists. It is probably something fairly basic but does anyone know what I might be doing wrong? If not can anyone give me any pointers to what might be different in the Core Data model after a save so I might have some clues why the fetch request stops working after saving?

    Read the article

  • Fetch Data using predicate. Retrieve single value.

    - by Mr. McPepperNuts
    XYZAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", entryToSearchFor]; 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]; NSArray *results = [managedObjectContext executeFetchRequest:request error:nil]; if (results == nil) { NSLog(@"No results found"); }else { NSLog(@"entryToSearchFor %@", entryToSearchFor); NSLog(@"results %@", [results objectAtIndex:0]); } I want to retrieve a single value (String) from "Entry." I believe I must be missing. Can someone point it out? Btw, the NSLog results outputs the following: results <NSManagedObject: 0x3d2d360> (entity: Entry; id: 0x3d13650 <x-coredata://6EA12ADA-8C0B-477F-801C-B44FE6E6C91C/Entry/p3> ; data: <fault>)

    Read the article

  • Altering ManagedObjects In NSArray

    - by Garry
    I have an entity called 'Job' with two boolean attributes named 'completed' and 'logged'. I am trying to retrieve all completed jobs that have not been logged at app start-up and change them to logged. I'm able to get all the completed but unlogged jobs with this fetchRequest: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(completed == %@ && logged == %@)", [NSNumber numberWithBool:YES], [NSNumber numberWithBool:NO]]; I'm then assigning this predicate to a fetchRequest and calling the [managedObjectContext executeFetchRequest:fetchRequest] method to get an array of all Job entities that meet this criteria. This seems to work fine and is returning the correct number of jobs. What I've been trying to do is loop through the NSArray returned, set the logged attribute to YES and then save. This seems to complete and doesn't return any errors but the changes are not persisted when the application quits. Where am I going wrong? [fetchRequest setPredicate:predicate]; NSError error; NSArray jobsToLog = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; if ([jobsToLog count] > 0) { for (int i = 0; i < [jobsToLog count] - 1; i++) { [[jobsToLog objectAtIndex:i] setLogged:[NSNumber numberWithBool:YES]]; // Commit the changes made to disk error = nil; if (![managedObjectContext save:&error]) { // An error occurred } } } Thanks in anticipation,

    Read the article

  • NSFetchedResultsController on secondary UITableView - how to query data?

    - by Jason
    I am creating a core-data based Navigation iPhone app with multiple screens. Let's say it is a flash-card application. The data model is very simple, with only two entities: Language, and CardSet. There is a one-to-many relationship between the Language entity and the CardSet entities, so each Language may contain multiple CardSets. In other words, Language has a one-to-many relationship Language.cardSets which points to the list of CardSets, and CardSet has a relationship CardSet.language which points to the Language. There are two screens: (1) An initial TableView screen, which displays the list of languages; and (2) a secondary TableView screen, which displays the list of CardSets in the Language. In the initial screen, which lists the languages, I am using NSFetchedResultsController to keep the list of languages up-to-date. The screen passes the Language selected to the secondary screen. On the secondary screen, I am trying to figure out whether I should again use an NSFetchedResultsController to maintain the list of CardSets, or if I should work through Language.cardSets to simply pull the list out of the object model. The latter makes the most sense programatically because I already have the Language - but then it would not automatically be updated on changes. I have looked at the NSFetchedResultsController documentation, and it seems like I can easily create predicates based on attributes - but not relationships. I.e., I can create the following NSFetchedResultsController: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE[c] 'Chuck Norris'"]; How can I access my data through the direct relationship - Language.cardSets - and also have the table auto-update using NSFetchedResultsController? Is this possible?

    Read the article

  • Is there a more memory efficient way to search through a Core Data database?

    - by Kristian K
    I need to see if an object that I have obtained from a CSV file with a unique identifier exists in my Core Data Database, and this is the code I deemed suitable for this task: NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity; entity = [NSEntityDescription entityForName:@"ICD9" inManagedObjectContext:passedContext]; [fetchRequest setEntity:entity]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"uniqueID like %@", uniqueIdentifier]; [fetchRequest setPredicate:pred]; NSError *err; NSArray* icd9s = [passedContext executeFetchRequest:fetchRequest error:&err]; [fetchRequest release]; if ([icd9s count] > 0) { for (int i = 0; i < [icd9s count]; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; NSString *name = [[icd9s objectAtIndex:i] valueForKey:@"uniqueID"]; if ([name caseInsensitiveCompare:uniqueIdentifier] == NSOrderedSame && name != nil) { [pool release]; return [icd9s objectAtIndex:i]; } [pool release]; } } return nil; After more thorough testing it appears that this code is responsible for a huge amount of leaking in the app I'm writing (it crashes on a 3GS before making it 20 percent through the 1459 items). I feel like this isn't the most efficient way to do this, any suggestions for a more memory efficient way? Thanks in advance!

    Read the article

  • Core Data combined Query

    - by Chris Summer
    Hey, i have question related to CoreData. My iphone project has 2 Entities, Organisation and Brand with a 1 to many "BrandsToOrg" relationship and inverse. So my project has a Mapview, where you can see all the Organisations and a little subview when you click on those Organisations.At the subview there is a "show Brands" Button, which should init a new TableView who only shows the brands belong to the seleceted organisation. Any ideas how i can code that? thx NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(TitleMedium == %@)",@"Rock Antenne"];???? NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:self.entityName inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; // If a predicate was passed, pass it to the query if(predicate != nil) { [request setPredicate:predicate]; } // If a sort key was passed, use it for sorting. NSString *sortKey=@"TitleMedium"; BOOL sortAscending=YES; if(sortKey != nil) { NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [sortDescriptors release]; [sortDescriptor release]; } NSError *error; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; [request release]; [self setEntityArray:mutableFetchResults];

    Read the article

  • How do I remove 3 characters from the end of an NSURL?

    - by saywhatman
    Hey, my first question! I've been able to code up most of this RSS reader without enlisting help (through a lot of searches through stackoverflow!) but I'm stumped here. NSString *urlbase = [[NSString alloc] initWithFormat:[links3 objectAtIndex:indexPath.row]]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlbase]]; NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet]; NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"]; NSArray *parts = [urlbase componentsSeparatedByCharactersInSet:whitespaces]; NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings]; urlbase = [filteredArray componentsJoinedByString:@" "]; NSLog(@"%@ %i" , urlbase, 4353); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlbase]]; The links3 array is a NSMutableArray with strings. The first few lines work flawlessly in eliminating the space at the beginning each string from that array, which is stored in 'urlbase' so they look fine when they come out. When we NSLog urlbase, we see: http://www.feedzilla.com/r/D7E6204FEDBFE541314B997AAB5D2DF9CBA2EFEE But, when we use: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlbase]] We see: http://www.feedzilla.com/r/D7E6204FEDBFE541314B997AAB5D2DF9CBA2EFEE%0A How can I fix this? Can I remove those tail elements somehow? Thanks!

    Read the article

  • Objective-C Out of scope problem

    - by davbryn
    Hi, I'm having a few problems with some Objective-C and would appreciate some pointers. So I have a class MapFileGroup which has the following simple interface (There are other member variables but they aren't important): @interface MapFileGroup : NSObject { NSMutableArray *mapArray; } @property (nonatomic, retain) NSMutableArray *mapArray; mapArray is @synthesize'd in the .m file. It has an init method: -(MapFileGroup*) init { self = [super init]; if (self) { mapArray = [NSMutableArray arrayWithCapacity: 10]; } return self; } It also has a method for adding a custom object to the array: -(BOOL) addMapFile:(MapFile*) mapfile { if (mapfile == nil) return NO; mapArray addObject:mapfile]; return YES; } The problem I get comes when I want to use this class - obviously due to a misunderstanding of memory management on my part. In my view controller I declare as follows: (in the @interface): MapFileGroup *fullGroupOfMaps; With @property @property (nonatomic, retain) MapFileGroup *fullGroupOfMaps; Then in the .m file I have a function called loadMapData that does the following: MapFileGroup *mapContainer = [[MapFileGroup alloc] init]; // create a predicate that we can use to filter an array // for all strings ending in .png (case insensitive) NSPredicate *caseInsensitivePNGFiles = [NSPredicate predicateWithFormat:@"SELF endswith[c] '.png'"]; mapNames = [unfilteredArray filteredArrayUsingPredicate:caseInsensitivePNGFiles]; [mapNames retain]; NSEnumerator * enumerator = [mapNames objectEnumerator]; NSString * currentFileName; NSString *nameOfMap; MapFile *mapfile; while(currentFileName = [enumerator nextObject]) { nameOfMap = [currentFileName substringToIndex:[currentFileName length]-4]; //strip the extension mapfile = [[MapFile alloc] initWithName:nameOfMap]; [mapfile retain]; // add to array [fullGroupOfMaps addMapFile:mapfile]; } This seems to work ok (Though I can tell I've not got the memory management working properly, I'm still learning Objective-C); however, I have an (IBAction) that interacts with the fullGroupOfMaps later. It calls a method within fullGroupOfMaps, but if I step into the class from that line while debugging, all fullGroupOfMaps's objects are now out of scope and I get a crash. So apologies for the long question and big amount of code, but I guess my main question it: How should I handle a class with an NSMutableArray as an instance variable? What is the proper way of creating objects to be added to the class so that they don't get freed before I'm done with them? Many thanks

    Read the article

  • Regex solution for Objective-C

    - by rjstelling
    What is the best method for using Regular Expressions within Objective-C? There seems to be some open source project that provide regex support, can any one recommend one? Also I looked at NSPredicate, can anyone suggest any regex examples? Background: I want use regex mainly for validation, IP's, email addresses, internal ID's etc

    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

  • MKMap showing detail of annotations

    - by yeohchan
    I have encountered a problem of populating the description for each annotation. Each annotation works, but there is somehow an area when trying to click on it. Here is the code. the one in bold is the one that has the problem. -(void)viewDidLoad{ FlickrFetcher *fetcher=[FlickrFetcher sharedInstance]; NSArray *rec=[fetcher recentGeoTaggedPhotos]; for(NSDictionary *dic in rec){ NSLog(@"%@",dic); NSDictionary *string = [fetcher locationForPhotoID:[dic objectForKey:@"id"]]; double latitude = [[string objectForKey:@"latitude"] doubleValue]; double longitude = [[string objectForKey:@"longitude"]doubleValue]; if(latitude !=0 && latitude != 0 ){ CLLocationCoordinate2D coordinate1 = { latitude,longitude }; **NSDictionary *adress=[NSDictionary dictionaryWithObjectsAndKeys:[dic objectForKey:@"owner"],[dic objectForKey:@"title"],nil];** MKPlacemark *anArea=[[MKPlacemark alloc]initWithCoordinate:coordinate1 addressDictionary:adress]; [mapView addAnnotation:anArea]; } } } Here is what the Flickr class does: #import <Foundation/Foundation.h> #define TEST_HIGH_NETWORK_LATENCY 0 typedef enum { FlickrFetcherPhotoFormatSquare, FlickrFetcherPhotoFormatLarge } FlickrFetcherPhotoFormat; @interface FlickrFetcher : NSObject { NSManagedObjectModel *managedObjectModel; NSManagedObjectContext *managedObjectContext; NSPersistentStoreCoordinator *persistentStoreCoordinator; } // Returns the 'singleton' instance of this class + (id)sharedInstance; // // Local Database Access // // Checks to see if any database exists on disk - (BOOL)databaseExists; // Returns the NSManagedObjectContext for inserting and fetching objects into the store - (NSManagedObjectContext *)managedObjectContext; // Returns an array of objects already in the database for the given Entity Name and Predicate - (NSArray *)fetchManagedObjectsForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate; // Returns an NSFetchedResultsController for a given Entity Name and Predicate - (NSFetchedResultsController *)fetchedResultsControllerForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate; // // Flickr API access // NOTE: these are blocking methods that wrap the Flickr API and wait on the results of a network request // // Returns an array of Flickr photo information for photos with the given tag - (NSArray *)photosForUser:(NSString *)username; // Returns an array of the most recent geo-tagged photos - (NSArray *)recentGeoTaggedPhotos; // Returns a dictionary of user info for a given user ID. individual photos contain a user ID keyed as "owner" - (NSString *)usernameForUserID:(NSString *)userID; // Returns the photo for a given server, id and secret - (NSData *)dataForPhotoID:(NSString *)photoID fromFarm:(NSString *)farm onServer:(NSString *)server withSecret:(NSString *)secret inFormat:(FlickrFetcherPhotoFormat)format; // Returns a dictionary containing the latitue and longitude where the photo was taken (among other information) - (NSDictionary *)locationForPhotoID:(NSString *)photoID; @end

    Read the article

  • Filter entire NSDictionaries out of NSArray based on multiple keys

    - by user270475
    Hi, I have an NSArray of NSDictionary objects which I would like to be able to return a new array of NSDictionaries from, where every NSDictionary has "Area == North" (for example). The closest example I have found so far is http://stackoverflow.com/questions/958622/using-nspredicate-to-filter-an-nsarray-based-on-nsdictionary-keys but this just returns the unique values for a given key, not the dictionary that has that key. Is there any way to perform a similar operation, and to return the entire dictionary?

    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

  • Bulk update & occasional insert (coredata) - Too slow

    - by Andrew
    Update: Currently looking into NSSET's minusSet links: http://stackoverflow.com/questions/1475636/comparing-two-arrays Hi guys, Could benefit from your wisdom here.. I'm using Coredata in my app, on first launch I download a data file and insert over 500 objects (each with 60 attributes) - fast, no problem. Each subsequent launch I download an updated version of the file, from which I need to update all existing objects' attributes (except maybe 5 attributes) and create new ones for items which have been added to the downloaded file. So, first launch I get 500 objects.. say a week later my file now contains 507 items.. I create two arrays, one for existing and one for downloaded. NSArray *peopleArrayDownloaded = [CoreDataHelper getObjectsFromContext:@"person" :@"person_id" :YES :managedObjectContextPeopleTemp]; NSArray *peopleArrayExisting = [CoreDataHelper getObjectsFromContext:@"person" :@"person_id" :YES :managedObjectContextPeople]; If the count of each array is equal then I just do this: NSUInteger index = 0; if ([peopleArrayExisting count] == [peopleArrayDownloaded count]) { NSLog(@"Number of people downloaded is same as the number of people existing"); for (person *existingPerson in peopleArrayExisting) { person *tempPerson = [peopleArrayDownloaded objectAtIndex:index]; // NSLog(@"Updating id: %@ with id: %@",existingPerson.person_id,tempPerson.person_id); // I have 60 attributes which I to update on each object, is there a quicker way other than overwriting existing? index++; } } else { NSLog(@"Number of people downloaded is different to number of players existing"); So now comes the slow part. I end up using this (which is tooooo slow): NSLog(@"Need people added to the league"); for (person *tempPerson in peopeArrayDownloaded) { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person_id = %@",tempPerson.person_id]; // NSLog(@"Searching for existing person, person_id: %@",existingPerson.person_id); NSArray *filteredArray = [peopleArrayExisting filteredArrayUsingPredicate:predicate]; if ([filteredArray count] == 0) { NSLog(@"Couldn't find an existing person in the downloaded file. Adding.."); person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"person" inManagedObjectContext:managedObjectContextPeople]; Is there a way to generate a new array of index items referring to the additional items in my downloaded file? Incidentally, on my tableViews I'm using NSFetchedResultsController so updating attributes will call [cell setNeedsDisplay]; .. about 60 times per cell, not a good thing and it can crash the app. Thanks for reading :)

    Read the article

  • Fixing predicated NSFetchedResultsController/NSFetchRequest performance with SQLite backend?

    - by Jaanus
    I have a series of NSFetchedResultsControllers powering some table views, and their performance on device was abysmal, on the order of seconds. Since it all runs on main thread, it's blocking my app at startup, which is not great. I investigated and turns out the predicate is the problem: NSPredicate *somePredicate = [NSPredicate predicateWithFormat:@"ANY somethings == %@", something]; [fetchRequest setPredicate:somePredicate]; I.e the fetch entity, call it "things", has a many-to-many relation with entity "something". This predicate is a filter that limits the results to only things that have a relation with a particular "something". When I removed the predicate for testing, fetch time (the initial performFetch: call) dropped (for some extreme cases) from 4 seconds to around 100ms or less, which is acceptable. I am troubled by this, though, as it negates a lot of the benefit I was hoping to gain with Core Data and NSFRC, which otherwise seems like a powerful tool. So, my question is, how can I optimize this performance? Am I using the predicate wrong? Should I modify the model/schema somehow? And what other ways there are to fix this? Is this kind of degraded performance to be expected? (There are on the order of hundreds of <1KB objects.) EDIT WITH DETAILS: Here's the code: [fetchRequest setFetchLimit:200]; NSLog(@"before fetch"); BOOL success = [frc performFetch:&error]; if (!success) { NSLog(@"Fetch request error: %@", error); } NSLog(@"after fetch"); Updated logs (previously, I had some application inefficiencies degrading the performance here. These are the updated logs that should be as close to optimal as you can get under my current environment): 2010-02-05 12:45:22.138 Special Ppl[429:207] before fetch 2010-02-05 12:45:22.144 Special Ppl[429:207] CoreData: sql: SELECT DISTINCT 0, t0.Z_PK, t0.Z_OPT, <model fields> FROM ZTHING t0 LEFT OUTER JOIN Z_1THINGS t1 ON t0.Z_PK = t1.Z_2THINGS WHERE t1.Z_1SOMETHINGS = ? ORDER BY t0.ZID DESC LIMIT 200 2010-02-05 12:45:22.663 Special Ppl[429:207] CoreData: annotation: sql connection fetch time: 0.5094s 2010-02-05 12:45:22.668 Special Ppl[429:207] CoreData: annotation: total fetch execution time: 0.5240s for 198 rows. 2010-02-05 12:45:22.706 Special Ppl[429:207] after fetch If I do the same fetch without predicate (by commenting out the two lines in the beginning of the question): 2010-02-05 12:44:10.398 Special Ppl[414:207] before fetch 2010-02-05 12:44:10.405 Special Ppl[414:207] CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, <model fields> FROM ZTHING t0 ORDER BY t0.ZID DESC LIMIT 200 2010-02-05 12:44:10.426 Special Ppl[414:207] CoreData: annotation: sql connection fetch time: 0.0125s 2010-02-05 12:44:10.431 Special Ppl[414:207] CoreData: annotation: total fetch execution time: 0.0262s for 200 rows. 2010-02-05 12:44:10.457 Special Ppl[414:207] after fetch 20-fold difference in times. 500ms is not that great, and there does not seem to be a way to do it in background thread or otherwise optimize that I can think of. (Apart from going to a binary store where this becomes a non-issue, so I might do that. Binary store performance is consistently ~100ms for the above 200-object predicated query.) (I nested another question here previously, which I now moved away).

    Read the article

  • Can't obtain reference to EKReminder array retrieved from fetchRemindersMatchingPredicate

    - by Scionwest
    When I create an NSPredicate via EKEventStore predicateForRemindersInCalendars; and pass it to EKEventStore fetchRemindersMatchingPredicate:completion:^ I can loop through the reminders array provided by the completion code block, but when I try to store a reference to the reminders array, or create a copy of the array into a local variable or instance variable, both array's remain empty. The reminders array is never copied to them. This is the method I am using, in the method, I create a predicate, pass it to the event store and then loop through all of the reminders logging their title via NSLog. I can see the reminder titles during runtime thanks to NSLog, but the local arrayOfReminders object is empty. I also try to add each reminder into an instance variable of NSMutableArray, but once I leave the completion code block, the instance variable remains empty. Am I missing something here? Can someone please tell me why I can't grab a reference to all of the reminders for use through-out the app? I am not having any issues at all accessing and storing EKEvents, but for some reason I can't do it with EKReminders. - (void)findAllReminders { NSPredicate *predicate = [self.eventStore predicateForRemindersInCalendars:nil]; __block NSArray *arrayOfReminders = [[NSArray alloc] init]; [self.eventStore fetchRemindersMatchingPredicate:predicate completion:^(NSArray *reminders) { arrayOfReminders = [reminders copy]; //Does not work. for (EKReminder *reminder in reminders) { [self.remindersForTheDay addObject:reminder]; NSLog(@"%@", reminder.title); } }]; //Always = 0; if ([self.remindersForTheDay count]) { NSLog(@"Instance Variable has reminders!"); } //Always = 0; if ([arrayOfReminders count]) { NSLog(@"Local Variable has reminders!"); } } The eventStore getter is where I perform my instantiation and get access to the event store. - (EKEventStore *)eventStore { if (!_eventStore) { _eventStore = [[EKEventStore alloc] init]; //respondsToSelector indicates iOS 6 support. if ([_eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { //Request access to user calendar [_eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (granted) { NSLog(@"iOS 6+ Access to EventStore calendar granted."); } else { NSLog(@"Access to EventStore calendar denied."); } }]; //Request access to user Reminders [_eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) { if (granted) { NSLog(@"iOS 6+ Access to EventStore Reminders granted."); } else { NSLog(@"Access to EventStore Reminders denied."); } }]; } else { //iOS 5.x and lower support if Selector is not supported NSLog(@"iOS 5.x < Access to EventStore calendar granted."); } for (EKCalendar *cal in self.calendars) { NSLog(@"Calendar found: %@", cal.title); } [_eventStore reset]; } return _eventStore; } Lastly, just to show that I am initializing my remindersForTheDay instance variable using lazy instantiation. - (NSMutableArray *)remindersForTheDay { if (!_remindersForTheDay) _remindersForTheDay = [[NSMutableArray alloc] init]; return _remindersForTheDay; } I've read through the Apple documentation and it doesn't provide any explanation that I can find to answer this. I read through the Blocks Programming docs and it states that you can access local and instance variables without issues from within a block, but for some reason, the above code does not work. Any help would be greatly appreciated, I've scoured Google for answers but have yet to get this figured out. Thanks everyone! Johnathon.

    Read the article

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