Search Results

Search found 173 results on 7 pages for 'reloaddata'.

Page 7/7 | < Previous Page | 3 4 5 6 7 

  • Updating DetailViewController from RootController

    - by Stefano Salmaso
    I'm trying to create an iPad application with a similar user interface to Apple's Mail application, i.e: RootView controller (table view) on the left hand side of the split view for navigation with a multiple view hierarchy. When a table cell is selected a new table view is pushed on the left hand side The new view on the left side can update the detail view. I can accomplish both tasks BUT NOT TOGETHER. I mean I can make a multi-level table view in the RootController.(HERE you can find the working source code). Or I can make a single-level table view in the RootController which can update the detailViewController (here there is the source code:http://www.megaupload.com/?d=D6L0463G). Can anyone tell me how to make a multi-level table in the RootController which can update a detailViewController? There is more source code at the link but below is the method in which I presume I have to declare a new detailViewController (which has to be put in the UISplitViewController): - (void)tableView:(UITableView *)TableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row]; //Get the children of the present item. NSArray *Children = [dictionary objectForKey:@"Children"]; // if([Children count] == 0) { /* Create and configure a new detail view controller appropriate for the selection. */ NSUInteger row = indexPath.row; UIViewController <SubstitutableDetailViewController> *detailViewController = nil; if (row == 0) { FirstDetailViewController *newDetailViewController = [[FirstDetailViewController alloc]initWithNibName:@"FirstDetailView" bundle:nil]; detailViewController = newDetailViewController; } if (row == 1) { SecondDetailViewController *newDetailViewController = [[SecondDetailViewController alloc]initWithNibName:@"SecondDetailView" bundle:nil]; detailViewController = newDetailViewController; } // Update the split view controller's view controllers array. NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, detailViewController, nil]; splitViewController.viewControllers = viewControllers//nothing happens..... [viewControllers release];// } else { //Prepare to tableview. RootViewController *rvController = [[RootViewController alloc]initWithNibName:@"RootViewController" bundle:[NSBundle mainBundle]]; //Increment the Current View rvController.current_level += 1; //Set the title; rvController.current_title = [dictionary objectForKey:@"Title"]; //Push the new table view on the stack [self.navigationController pushViewController:rvController animated:YES]; rvController.tableDataSource = Children; [rvController.tableView reloadData]; //without this instrucion,items won't be loaded inside the second level of the table [rvController release]; } }

    Read the article

  • Issues declaring already existing NSMutableArray in new class

    - by Graeme
    I have a class (DataImporter) which has the code to download an RSS feed. I also have a view and separate class (TableView) which displays the data in a UITableView and starts the parsing process, storing parsed information in an NSMutableArray (items) which is located in the (TableView) subclass. Now I wish to add a UIMapView which displays the items in the (items) NSMutableArray. Herein lies the issue - I need to somehow get the data from the (items) NSMutableArray into the new (mapView) subclass which I'm struggling with - and I preferably don't want to have to create a new class to download the data again for the mapView class when it already is in the applications memory. Is there a way I can transfer the information from the NSMutableArray (items) class to the (mapView) class (i.e. how do I declare the NSMutableArray in the (mapView) class)? Here's a overview of how the system works: App opened Data downloaded (using DataImporter class) when (TableView) viewDidLoad runs Data stored in NSMutableArray accessible by the (TableView) class And from here I need to access and declare the array from a new (mapView) class. Any help greatly appreciated, thanks. Code for viewDidLoad MapKit: Data *data = nil; NSString *ilocation = [data locations]; NSString *ilocation2 = @"New Zealand"; NSString *inewlString; inewlString = [ilocation stringByAppendingString:ilocation2]; NSLog(@"inewlString=%@",inewlString); if(forwardGeocoder == nil) { forwardGeocoder = [[BSForwardGeocoder alloc] initWithDelegate:self]; } // Forward geocode! [forwardGeocoder findLocation: inewlString]; Code for parsing data into original NSMutable Array: - (void)beginParsing { NSLog(@"Parsing has begun"); //self.navigationItem.rightBarButtonItem.enabled = NO; // Allocate the array for song storage, or empty the results of previous parses if (incidents == nil) { NSLog(@"Grabbing array"); self.datas = [NSMutableArray array]; } else { [datas removeAllObjects]; [self.tableView reloadData]; } // Create the parser, set its delegate, and start it. self.parser = [[DataImporter alloc] init]; parser.delegate = self; [parser start]; }

    Read the article

  • Drill down rss reader iphone

    - by bing
    Hi everyone, I have made a simple rss reader. The app loads an xml atom file in an array. Now I have added categories to my atom feed, which are first loaded in the array What is the best way to add drill down functionality programmatically. Now only the categories are loaded into the array and displayed. This is the implementation code ..... loading xml file <snip> ..... - (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"found file and started parsing"); } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]]; NSLog(@"error parsing XML: %@", errorString); UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [errorAlert show]; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ //NSLog(@"found this element: %@", elementName); currentElement = [elementName copy]; if ([elementName isEqualToString:@"entry"]) { // clear out our story item caches... Categoryentry = [[NSMutableDictionary alloc] init]; currentID = [[NSMutableString alloc] init]; currentTitle = [[NSMutableString alloc] init]; currentSummary = [[NSMutableString alloc] init]; currentContent = [[NSMutableString alloc] init]; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ //NSLog(@"ended element: %@", elementName); if ([elementName isEqualToString:@"entry"]) { // save values to an entry, then store that item into the array... [Categoryentry setObject:currentTitle forKey:@"title"]; [Categoryentry setObject:currentID forKey:@"id"]; [Categoryentry setObject:currentSummary forKey:@"summary"]; [Categoryentry setObject:currentContent forKey:@"content"]; [categories addObject:[Categoryentry copy]]; NSLog(@"adding category: %@", currentTitle); } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ //NSLog(@"found characters: %@", string); // save the characters for the current item... if ([currentElement isEqualToString:@"title"]) { [currentTitle appendString:string]; } else if ([currentElement isEqualToString:@"id"]) { [currentID appendString:string]; } else if ([currentElement isEqualToString:@"summary"]) { [currentSummary appendString:string]; } else if ([currentElement isEqualToString:@"content"]) { [currentContent appendString:string]; } } - (void)parserDidEndDocument:(NSXMLParser *)parser { [activityIndicator stopAnimating]; [activityIndicator removeFromSuperview]; NSLog(@"all done!"); NSLog(@"categories array has %d entries", [categories count]); [newsTable reloadData]; }

    Read the article

  • Make sense of Notification Watcher source objective-c

    - by Chris
    From Notification Watcher source. - (void)selectNotification:(NSNotification*)aNotification { id sender = [aNotification object]; [selectedDistNotification release]; selectedDistNotification = nil; [selectedWSNotification release]; selectedWSNotification = nil; NSNotification **targetVar; NSArray **targetList; if (sender == distNotificationList) { targetVar = &selectedDistNotification; targetList = &distNotifications; } else { targetVar = &selectedWSNotification; targetList = &wsNotifications; } if ([sender selectedRow] != -1) { [*targetVar autorelease]; *targetVar = [[*targetList objectAtIndex:[sender selectedRow]] retain]; } if (*targetVar == nil) { [objectText setStringValue:@""]; } else { id obj = [*targetVar object]; NSMutableAttributedString *objStr = nil; if (obj == nil) { NSFont *aFont = [objectText font]; NSDictionary *attrDict = italicAttributesForFont(aFont); objStr = [[NSMutableAttributedString alloc] initWithString:@"(null)" attributes:attrDict]; } else { /* Line 1 */ objStr = [[NSMutableAttributedString alloc] initWithString: [NSString stringWithFormat:@" (%@)", [obj className]]]; [objStr addAttributes:italicAttributesForFont([objectText font]) range:NSMakeRange(1,[[obj className] length]+2)]; if ([obj isKindOfClass:[NSString class]]) { [objStr replaceCharactersInRange:NSMakeRange(0,0) withString:obj]; } else if ([obj respondsToSelector:@selector(stringValue)]) { [objStr replaceCharactersInRange:NSMakeRange(0,0) withString:[obj performSelector:@selector(stringValue)]]; } else { // Remove the space since we have no value to display [objStr replaceCharactersInRange:NSMakeRange(0,1) withString:@""]; } } [objectText setObjectValue:objStr]; /* LINE 2 */ [objStr release]; } [userInfoList reloadData]; } Over at //LINE 2 objStr is being released. Is this because we are assigning it with alloc in //LINE 1? Also, why is //LINE 1 not: objStr = [NSMutableAttributedString* initWithString:@"(null)" attributes:attrDict] If I create a new string like (NSString*) str = [NSString initWithString:@"test"]; ... str = @"another string"; Would I have to release str, or is this wrong and if I do that I have to use [[NSString alloc] initWithString:@"test"]? Why isn't the pointer symbol used as in [[NSString* alloc] ...? Thanks

    Read the article

  • NSMutableDictionary confused over how to use keys with certain code ?

    - by Jules
    I'm getting data from a database and I need to add the string field value and the record id. However, I need this to work with some existing code... I'm replacing this (see code below) and getting data from my database. NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path]; self.allCategories = dict; [dict release]; But needs to work with these key and value search functions. - (void)resetSearch { NSMutableDictionary *allCategoriesCopy = [self.allCategories mutableDeepCopy]; self.Categories = allCategoriesCopy; [allCategoriesCopy release]; NSMutableArray *keyArray = [[NSMutableArray alloc] init]; [keyArray addObject:UITableViewIndexSearch]; [keyArray addObjectsFromArray:[[self.allCategories allKeys] sortedArrayUsingSelector:@selector(compare:)]]; self.keys = keyArray; [keyArray release]; } . - (void)handleSearchForTerm:(NSString *)searchTerm { NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init]; [self resetSearch]; for (NSString *key in self.keys) { NSMutableArray *array = [Categories valueForKey:key]; NSMutableArray *toRemove = [[NSMutableArray alloc] init]; for (NSString *name in array) { if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound) [toRemove addObject:name]; } if ([array count] == [toRemove count]) [sectionsToRemove addObject:key]; [array removeObjectsInArray:toRemove]; [toRemove release]; } [self.keys removeObjectsInArray:sectionsToRemove]; [sectionsToRemove release]; [table reloadData]; } Keep getting an error from this code... NSDictionary *arrayTmp= [[NSDictionary alloc] init]; ... loop records int cid = sqlite3_column_int(statementTMP, 0); NSString *category = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)]; [arrayTmp setObject:category forKey:[NSString stringWithFormat:@"%i", cid]]; Error caused by line above * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString count]: unrecognized selector sent to instance 0x4d4c500' * Call stack at first throw * ... end loop self.allCategories = arrayTmp; [arrayTmp release];

    Read the article

  • UITableView crashes when trying to scroll

    - by Ondrej
    Hi, I have a problem with data in UITableView. I have UIViewController, that contains UITableView outlet and few more things I am using and ... It works :) ... it works lovely, but ... I've created an RSS reader class that is using delegates to deploy the data to the table ... and once again, If I'll just create dummy data in the main controller everything works! problem is with this line: rss.delegate = self; Preview looks a little bit broken than here are those RSS reader files on Google code: (Link to the header file on GoogleCode) (Link to the implementation file on Google code) viewDidLoad function of my controller: IGDataRss20 *rss = [[[IGDataRss20 alloc] init] autorelease]; rss.delegate = self; [rss initWithContentsOfUrl:@"http://rss.cnn.com/rss/cnn_topstories.rss"]; and my delegate methods: - (void)parsingEnded:(NSArray *)result { super.data = [[NSMutableArray alloc] initWithArray:result]; NSLog(@"My Items: %d", [super.data count]); [super.table reloadData]; NSLog(@"Parsing ended"); } (void)parsingError:(NSString *)message { NSLog(@"MyMessage: %@", message); } (void)parsingStarted:(NSXMLParser *)parser { NSLog(@"Parsing started"); } Just to clarify, NSLog(@"Parsing ended"); is being executed and I have 10 items in the array. Ok, here's my RSS reader header file: @class IGDataRss20; @protocol IGDataRss20Delegate @optional (void)parsingStarted:(NSXMLParser *)parser; (void)parsingError:(NSString *)message; (void)parsingEnded:(NSArray *)result; @end @interface IGDataRss20 : NSObject { NSXMLParser *rssParser; NSMutableArray *data; NSMutableDictionary *currentItem; NSString *currentElement; id <IGDataRss20Delegate> delegate; } @property (nonatomic, retain) NSMutableArray *data; @property (nonatomic, assign) id delegate; (void)initWithContentsOfUrl:(NSString *)rssUrl; (void)initWithContentsOfData:(NSData *)inputData; @end And this RSS reader implementation file: #import "IGDataRss20.h" @implementation IGDataRss20 @synthesize data, delegate; (void)initWithContentsOfUrl:(NSString *)rssUrl { self.data = [[NSMutableArray alloc] init]; NSURL *xmlURL = [NSURL URLWithString:rssUrl]; rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; } (void)initWithContentsOfData:(NSData *)inputData { self.data = [[NSMutableArray alloc] init]; rssParser = [[NSXMLParser alloc] initWithData:inputData]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; } (void)parserDidStartDocument:(NSXMLParser *)parser { [[self delegate] parsingStarted:parser]; } (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSString * errorString = [NSString stringWithFormat:@"Unable to parse RSS feed (Error code %i )", [parseError code]]; NSLog(@"Error parsing XML: %@", errorString); if ([parseError code] == 31) NSLog(@"Error code 31 is usually caused by encoding problem."); [[self delegate] parsingError:errorString]; } (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { currentElement = [elementName copy]; if ([elementName isEqualToString:@"item"]) currentItem = [[NSMutableDictionary alloc] init]; } (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"item"]) { [data addObject:(NSDictionary *)[currentItem copy]]; } } (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (![currentItem objectForKey:currentElement]) [currentItem setObject:[[[NSMutableString alloc] init] autorelease] forKey:currentElement]; [[currentItem objectForKey:currentElement] appendString:string]; } (void)parserDidEndDocument:(NSXMLParser *)parser { //NSLog(@"RSS array has %d items: %@", [data count], data); [[self delegate] parsingEnded:(NSArray *)self.data]; } (void)dealloc { [data, delegate release]; [super dealloc]; } @end Hope someone will be able to help me as I am becoming to be quite desperate, and I thought I am not already such a greenhorn :) Thanks, Ondrej

    Read the article

  • Freezes (not crashes) with GCD, blocks and Core Data

    - by Lukasz
    I have recently rewritten my Core Data driven database controller to use Grand Central Dispatch to manage fetching and importing in the background. Controller can operate on 2 NSManagedContext's: NSManagedObjectContext *mainMoc instance variable for main thread. this contexts is used only by quick access for UI by main thread or by dipatch_get_main_queue() global queue. NSManagedObjectContext *bgMoc for background tasks (importing and fetching data for NSFetchedresultsController for tables). This background tasks are fired ONLY by user defined queue: dispatch_queue_t bgQueue (instance variable in database controller object). Fetching data for tables is done in background to not block user UI when bigger or more complicated predicates are performed. Example fetching code for NSFetchedResultsController in my table view controllers: -(void)fetchData{ dispatch_async([CDdb db].bgQueue, ^{ NSError *error = nil; [[self.fetchedResultsController fetchRequest] setPredicate:self.predicate]; if (self.fetchedResultsController && ![self.fetchedResultsController performFetch:&error]) { NSSLog(@"Unresolved error in fetchData %@", error); } if (!initial_fetch_attampted)initial_fetch_attampted = YES; fetching = NO; dispatch_async(dispatch_get_main_queue(), ^{ [self.table reloadData]; [self.table scrollRectToVisible:CGRectMake(0, 0, 100, 20) animated:YES]; }); }); } // end of fetchData function bgMoc merges with mainMoc on save using NSManagedObjectContextDidSaveNotification: - (void)bgMocDidSave:(NSNotification *)saveNotification { // CDdb - bgMoc didsave - merging changes with main mainMoc dispatch_async(dispatch_get_main_queue(), ^{ [self.mainMoc mergeChangesFromContextDidSaveNotification:saveNotification]; // Extra notification for some other, potentially interested clients [[NSNotificationCenter defaultCenter] postNotificationName:DATABASE_SAVED_WITH_CHANGES object:saveNotification]; }); } - (void)mainMocDidSave:(NSNotification *)saveNotification { // CDdb - main mainMoc didSave - merging changes with bgMoc dispatch_async(self.bgQueue, ^{ [self.bgMoc mergeChangesFromContextDidSaveNotification:saveNotification]; }); } NSfetchedResultsController delegate has only one method implemented (for simplicity): - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { dispatch_async(dispatch_get_main_queue(), ^{ [self fetchData]; }); } This way I am trying to follow Apple recommendation for Core Data: 1 NSManagedObjectContext per thread. I know this pattern is not completely clean for at last 2 reasons: bgQueue not necessarily fires the same thread after suspension but since it is serial, it should not matter much (there is never 2 threads trying access bgMoc NSManagedObjectContext dedicated to it). Sometimes table view data source methods will ask NSFetchedResultsController for info from bgMoc (since fetch is done on bgQueue) like sections count, fetched objects in section count, etc.... Event with this flaws this approach works pretty well of the 95% of application running time until ... AND HERE GOES MY QUESTION: Sometimes, very randomly application freezes but not crashes. It does not response on any touch and the only way to get it back to live is to restart it completely (switching back to and from background does not help). No exception is thrown and nothing is printed to the console (I have Breakpoints set for all exception in Xcode). I have tried to debug it using Instruments (time profiles especially) to see if there is something hard going on on main thread but nothing is showing up. I am aware that GCD and Core Data are the main suspects here, but I have no idea how to track / debug this. Let me point out, that this also happens when I dispatch all the tasks to the queues asynchronously only (using dispatch_async everywhere). This makes me think it is not just standard deadlock. Is there any possibility or hints of how could I get more info what is going on? Some extra debug flags, Instruments magical tricks or build setting etc... Any suggestions on what could be the cause are very much appreciated as well as (or) pointers to how to implement background fetching for NSFetchedResultsController and background importing in better way.

    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

  • NSOperation unable to load data on the TableView

    - by yeohchan
    I have a problem in NSOperation. I tried many ways but it would run behind the screen, but will not make it appear on the my table view. Can anyone help me out with this. I am new to NSOperation. Recents.h #import <UIKit/UIKit.h> #import "FlickrFetcher.h" @interface Recents : UITableViewController { FlickrFetcher *fetcher; NSString *name; NSData *picture; NSString *picName; NSMutableArray *names; NSMutableArray *pics; NSMutableArray *lists; NSArray *namelists; NSOperationQueue *operationQueue; } @property (nonatomic,retain)NSString *name; @property (nonatomic,retain)NSString *picName; @property (nonatomic,retain)NSData *picture; @property (nonatomic,retain)NSMutableArray *names; @property (nonatomic,retain)NSMutableArray *pics; @property(nonatomic,retain)NSMutableArray *lists; @property(nonatomic,retain)NSArray *namelists; @end Recents.m #import "Recents.h" #import "PersonList.h" #import "PhotoDetail.h" @implementation Recents @synthesize picName,picture,name,names,pics,lists,namelists; // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization self.title=@"Recents"; } return self; } - (void)beginLoadingFlickrData{ NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(synchronousLoadFlickrData) object:nil]; [operationQueue addOperation:operation]; [operation release]; } - (void)synchronousLoadFlickrData{ fetcher=[FlickrFetcher sharedInstance]; NSArray *recents=[fetcher recentGeoTaggedPhotos]; [self performSelectorOnMainThread:@selector(didFinishLoadingFlickrDataWithResults:) withObject:recents waitUntilDone:NO]; } - (void)didFinishLoadingFlickrDataWithResults:(NSArray *)recents{ for(NSDictionary *dic in recents){ [names addObject:[fetcher usernameForUserID:[dic objectForKey:@"owner"]]]; if([[dic objectForKey:@"title"]isEqualToString:@""]){ [pics addObject:@"Untitled"]; }else{ [pics addObject:[dic objectForKey:@"title"]]; } NSLog(@"OK!!"); } [self.tableView reloadData]; [self.tableView flashScrollIndicators]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; operationQueue = [[NSOperationQueue alloc] init]; [operationQueue setMaxConcurrentOperationCount:1]; [self beginLoadingFlickrData]; self.tableView.rowHeight = 95; } /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [super dealloc]; } #pragma mark - #pragma mark Table View Data Source Methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return[names count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIdentifier] autorelease]; } cell.detailTextLabel.text=[names objectAtIndex:indexPath.row]; cell.textLabel.text=[pics objectAtIndex:indexPath.row]; //UIImage *image=[UIImage imageWithData:[self.lists objectAtIndex:indexPath.row]]; //cell.imageView.image=image; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { fetcher=[[FlickrFetcher alloc]init]; PhotoDetail *scroll=[[PhotoDetail alloc]initWithNibName:@"PhotoDetail" bundle:nil]; scroll.titleName=[self.pics objectAtIndex:indexPath.row]; scroll.picture = [UIImage imageWithData:[self.lists objectAtIndex:indexPath.row]]; [self.navigationController pushViewController:scroll animated:YES]; }

    Read the article

  • data not reloading into tableview from core data on minor update

    - by Martin KS
    I've got a basic photo album application, on the first view a list of albums is displayed with a subtitle showing how many images are in each album. I've got everything working to add albums, and add images to albums. The problem is that the image count lines are accurate whenever the app loads, but I can't get them to update during execution. The following viewdidload correctly populates all lines of the tableview when the app loads: - (void)viewDidLoad { [super viewDidLoad]; // Set the title. self.title = @"Photo albums"; // Configure the add and edit buttons. self.navigationItem.leftBarButtonItem = self.editButtonItem; addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAlbum)]; addButton.enabled = YES; self.navigationItem.rightBarButtonItem = addButton; /* Fetch existing albums. Create a fetch request; find the Album entity and assign it to the request; add a sort descriptor; then execute the fetch. */ NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; // Order the albums by name. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"albumName" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [sortDescriptor release]; [sortDescriptors release]; // Execute the fetch -- create a mutable copy of the result. NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. } LocationsAppDelegate *mainDelegate = (LocationsAppDelegate *)[[UIApplication sharedApplication] delegate]; // Set master albums array to the mutable array, then clean up. [mainDelegate setAlbumsArray:mutableFetchResults]; [mutableFetchResults release]; [request release]; } But when I run similar code inside viewdidappear, nothing happens: { /* Fetch existing albums. Create a fetch request; find the Album entity and assign it to the request; add a sort descriptor; then execute the fetch. */ NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; // Order the albums by creation date, most recent first. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"albumName" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [sortDescriptor release]; [sortDescriptors release]; // Execute the fetch -- create a mutable copy of the result. NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. } LocationsAppDelegate *mainDelegate = (LocationsAppDelegate *)[[UIApplication sharedApplication] delegate]; // Set master albums array to the mutable array, then clean up. [mainDelegate setAlbumsArray:mutableFetchResults]; [self.tableView reloadData]; [mutableFetchResults release]; [request release]; } Apologies if I've missed the answer to this question elsewhere, but what am I missing?

    Read the article

  • iPhone App Crashes when merging managed object contexts

    - by DVG
    Short Version: Using two managed object contexts, and while the context is saving to the store the application bombs when I attempt to merge the two contexts and reload the table view. Long Version: Okay, so my application is set up as thus. 3 view controllers, all table views. Platforms View Controller - Games View Controller (Predicated upon platform selection) - Add Game View Controller I ran into a problem when Games View Controller was bombing when adding a new entry to the context, because the fetched results contorller wanted to update the view for something that didn't match the predicate. As a solution, I rebuilt the Add Controller to use a second NSManagedObject Context, called adding context, following the design pattern in the Core Data Books example. My Games List View Controller is a delegate for the add controller, to handle all the saving, so my addButtonPressed method looks like this - (IBAction) addButtonPressed: (id) sender { AddGameTableViewController *addGameVC = [[AddGameTableViewController alloc] initWithNibName:@"AddGameTableViewController" bundle:nil]; NSManagedObjectContext *aAddingContext = [[NSManagedObjectContext alloc] init]; self.addingContext = aAddingContext; [aAddingContext release]; [addingContext setPersistentStoreCoordinator:[[gameResultsController managedObjectContext] persistentStoreCoordinator]]; addGameVC.context = addingContext; addGameVC.delegate = self; addGameVC.newGame = (Game *)[NSEntityDescription insertNewObjectForEntityForName:@"Game" inManagedObjectContext:addingContext]; UINavigationController *addNavCon = [[UINavigationController alloc] initWithRootViewController:addGameVC]; [self presentModalViewController:addNavCon animated:YES]; [addGameVC release]; [addNavCon release]; } There is also a delegate method which handles the saving. This all works swimmingly. The issue is getting the table view controller in the GameListViewController to update itself. Per the example, an observer is added to watch for the second context to be saved, and then to merge the addingContext with the primary one. So I have: - (void)addViewController:(AddGameTableViewController *)controller didFinishWithSave:(BOOL)save { if (save) { NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter]; [dnc addObserver:self selector:@selector(addControllerContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:addingContext]; //snip! Context Save Code [dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:addingContext]; } self.addingContext = nil; [self dismissModalViewControllerAnimated:YES]; } - (void)addControllerContextDidSave:(NSNotification*)saveNotification { NSManagedObjectContext *myContext = [gameResultsController managedObjectContext]; [myContext mergeChangesFromContextDidSaveNotification:saveNotification]; } So now, what happens is after save is pressed, the application hangs for a moment and then crashes. The save is processed, as the new game is present when I relaunch the application, and the application seems to be flowing as appropriate, but it bombs out for reasons that are beyond my understanding. NSLog of the saveNotification spits out this: NSConcreteNotification 0x3b557f0 {name = NSManagingContextDidSaveChangesNotification; object = <NSManagedObjectContext: 0x3b4bb90>; userInfo = { inserted = {( <Game: 0x3b4f510> (entity: Game; id: 0x3b614e0 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Game/p2> ; data: { name = "Final Fantasy XIII"; platform = 0x3b66910 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Platform/p20>; }) )}; updated = {( <Platform: 0x3b67650> (entity: Platform; id: 0x3b66910 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Platform/p20> ; data: { games = ( 0x3b614e0 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Game/p2>, 0x603a530 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Game/p1> ); name = "Xbox 360"; }) )}; }} I've tried both a simple [self.tableView reloadData]; and the more complicated multi-method table updating structure in the Core Data Books example. Both produce the same result.

    Read the article

  • jQuery encoding values differently than expected for jQuery.ajax data elements

    - by Adam Tuttle
    I'm using jQuery.ajax() to make a PUT request to a REST web service, but seeing some really strange serialization behavior. (Before you say it: Yes, I know that not all browsers support PUT -- this is just an example implementation for an api/framework, and ultimately will not be called by a browser, but rather by a server-side library that does support the extra http verbs.) Here's the form: <form action="/example/api/artist" method="put" id="update"> First Name: <input type="text" name="firstname" /><br/> Last Name: <input type="text" name="lastname" /><br/> Address: <input type="text" name="address" /><br/> City: <input type="text" name="city" /><br/> State: <input type="text" name="state" /><br/> Postal Code: <input type="text" name="postalcode" /><br/> Email: <input type="text" name="email" /><br/> Phone: <input type="text" name="phone" /><br/> Fax: <input type="text" name="fax" /><br/> Password: <input type="text" name="thepassword" /><br/> <input type="hidden" name="debug" value="true" /> <input type="submit" value="Update Artist" /> <input type="reset" value="Cancel" id="updateCancel" /> </form> And the JS: $("#update").submit(function(e){ e.preventDefault(); var frm = $(this); $.ajax({ url: frm.attr('action'), data:{ firstname: $("#update input[name=firstname]").val(), lastname: $("#update input[name=lastname]").val(), address: $("#update input[name=address]").val(), city: $("#update input[name=city]").val(), state: $("#update input[name=state]").val(), postalcode: $("#update input[name=postalcode]").val(), email: $("#update input[name=email]").val(), phone: $("#update input[name=phone]").val(), fax: $("#update input[name=fax]").val(), thepassword: $("#update input[name=thepassword]").val() }, type: frm.attr('method'), dataType: "json", contentType: "application/json", success: function (data, textStatus, xhr){ console.log(data); reloadData(); }, error: function (xhr, textStatus, err){ console.log(textStatus); console.log(err); } }); }); When using FireBug, I see the request go through as this: firstname=Austin&lastname=Weber&address=25463+Main+Street%2C+Suite+C&city=Berkeley&state=CA&postalcode=94707-4513&email=austin%40life.com&phone=555-513-4318&fax=510-513-4888&thepassword=nopolyes That's not horrible, but ideally I'd rather get %20 instead of + for spaces. I tried wrapping each field value lookup in an escape: firstname: escape($("#update input[name=firstname]").val()) But that makes things worse: firstname=Austin&lastname=Weber&address=25463%2520Main%2520Street%252C%2520Suite%2520C&city=Berkeley&state=CA&postalcode=94707-4513&email=austin%40life.com&phone=555-513-4318&fax=510-513-4888&thepassword=nopolyes In this case, the value is being escaped twice; so first the space is encoded to %20, and then the % sign is escaped to %25 resulting in the %2520 for spaces, and %252C for the comma in the address field. What am I doing wrong here?

    Read the article

  • Find out when all processes in (void) is done?

    - by Emil
    Hey. I need to know how you can find out when all processes (loaded) from a - (void) are done, if it's possible. Why? I'm loading in data for a UITableView, and I need to know when a Loading... view can be replaced with the UITableView, and when I can start creating the cells. This is my code: - (void) reloadData { NSAutoreleasePool *releasePool = [[NSAutoreleasePool alloc] init]; NSLog(@"Reloading data."); NSURL *urlPosts = [NSURL URLWithString:[NSString stringWithFormat:@"%@", URL]]; NSError *lookupError = nil; NSString *data = [[NSString alloc] initWithContentsOfURL:urlPosts encoding:NSUTF8StringEncoding error:&lookupError]; postsData = [data componentsSeparatedByString:@"~"]; [data release], data = nil; urlPosts = nil; self.numberOfPosts = [[postsData objectAtIndex:0] intValue]; self.postsArrayID = [[postsData objectAtIndex:1] componentsSeparatedByString:@"#"]; self.postsArrayDate = [[postsData objectAtIndex:2] componentsSeparatedByString:@"#"]; self.postsArrayTitle = [[postsData objectAtIndex:3] componentsSeparatedByString:@"#"]; self.postsArrayComments = [[postsData objectAtIndex:4] componentsSeparatedByString:@"#"]; self.postsArrayImgSrc = [[postsData objectAtIndex:5] componentsSeparatedByString:@"#"]; NSMutableArray *writeToPlist = [NSMutableArray array]; NSMutableArray *writeToNoImagePlist = [NSMutableArray array]; NSMutableArray *imagesStored = [NSMutableArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"]]; int loop = 0; for (NSString *postID in postsArrayID) { if ([imagesStored containsObject:[NSString stringWithFormat:@"%@.png", postID]]){ NSLog(@"Allready stored, jump to next. ID: %@", postID); continue; } NSLog(@"%@.png", postID); NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[postsArrayImgSrc objectAtIndex:loop]]]; // If image contains anything, set cellImage to image. If image is empty, try one more time or use noImage.png, set in IB if (imageData == nil){ NSLog(@"imageData is empty before trying .jpeg"); // If image == nil, try to replace .jpg with .jpeg, and if that worked, set cellImage to that image. If that is also nil, use noImage.png, set in IB. imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[postsArrayImgSrc objectAtIndex:loop] stringByReplacingOccurrencesOfString:@".jpg" withString:@".jpeg"]]]; } if (imageData != nil){ NSLog(@"imageData is NOT empty when creating file"); [fileManager createFileAtPath:[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"images/%@.png", postID]] contents:imageData attributes:nil]; [writeToPlist addObject:[NSString stringWithFormat:@"%@.png", postID]]; } else { [writeToNoImagePlist addObject:[NSString stringWithFormat:@"%@", postID]]; } imageData = nil; loop++; NSLog(@"imagePlist: %@\nnoImagePlist: %@", writeToPlist, writeToNoImagePlist); } NSMutableArray *writeToAllPlist = [NSMutableArray arrayWithArray:writeToPlist]; [writeToPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:nowPlist]]; [writeToAllPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"]]]; [writeToNoImagePlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"noImage.plist"]]]; [writeToPlist writeToFile:nowPlist atomically:YES]; [writeToAllPlist writeToFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"] atomically:YES]; [writeToNoImagePlist writeToFile:[rootPath stringByAppendingPathComponent:@"noImage.plist"] atomically:YES]; [releasePool release]; }

    Read the article

  • Iphone NSXMLParser NSCFString memory leak

    - by atticusalien
    I am building an app that parses an rss feed. In the app there are two different types of feeds with different names for the elements in the feed, so I have created an NSXMLParser NSObject that takes the name of the elements of each feed before parsing. Here is my code: NewsFeedParser.h #import @interface NewsFeedParser : NSObject { NSInteger NewsSelectedCategory; NSXMLParser *NSXMLNewsParser; NSMutableArray *newsCategories; NSMutableDictionary *NewsItem; NSMutableString *NewsCurrentElement, *NewsCurrentElement1, *NewsCurrentElement2, *NewsCurrentElement3; NSString *NewsItemType, *NewsElement1, *NewsElement2, *NewsElement3; NSInteger NewsNumElements; } - (void) parseXMLFileAtURL:(NSString *)URL; @property(nonatomic, retain) NSString *NewsItemType; @property(nonatomic, retain) NSString *NewsElement1; @property(nonatomic, retain) NSString *NewsElement2; @property(nonatomic, retain) NSString *NewsElement3; @property(nonatomic, retain) NSMutableArray *newsCategories; @property(assign, nonatomic) NSInteger NewsNumElements; @end NewsFeedParser.m #import "NewsFeedParser.h" @implementation NewsFeedParser @synthesize NewsItemType; @synthesize NewsElement1; @synthesize NewsElement2; @synthesize NewsElement3; @synthesize newsCategories; @synthesize NewsNumElements; - (void)parserDidStartDocument:(NSXMLParser *)parser{ } - (void)parseXMLFileAtURL:(NSString *)URL { newsCategories = [[NSMutableArray alloc] init]; URL = [URL stringByReplacingOccurrencesOfString:@" " withString:@""]; URL = [URL stringByReplacingOccurrencesOfString:@"\n" withString:@""]; URL = [URL stringByReplacingOccurrencesOfString:@" " withString:@""]; //you must then convert the path to a proper NSURL or it won't work NSURL *xmlURL = [NSURL URLWithString:URL]; // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error // this may be necessary only for the toolchain [[NSURLCache sharedURLCache] setMemoryCapacity:0]; [[NSURLCache sharedURLCache] setDiskCapacity:0]; NSXMLNewsParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks. [NSXMLNewsParser setDelegate:self]; // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser. [NSXMLNewsParser setShouldProcessNamespaces:NO]; [NSXMLNewsParser setShouldReportNamespacePrefixes:NO]; [NSXMLNewsParser setShouldResolveExternalEntities:NO]; [NSXMLNewsParser parse]; [NSXMLNewsParser release]; } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]]; NSLog(@"error parsing XML: %@", errorString); UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [errorAlert show]; [errorAlert release]; [errorString release]; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NewsCurrentElement = [elementName copy]; if ([elementName isEqualToString:NewsItemType]) { // clear out our story item caches... NewsItem = [[NSMutableDictionary alloc] init]; NewsCurrentElement1 = [[NSMutableString alloc] init]; NewsCurrentElement2 = [[NSMutableString alloc] init]; if(NewsNumElements == 3) { NewsCurrentElement3 = [[NSMutableString alloc] init]; } } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ if ([elementName isEqualToString:NewsItemType]) { // save values to an item, then store that item into the array... [NewsItem setObject:NewsCurrentElement1 forKey:NewsElement1]; [NewsItem setObject:NewsCurrentElement2 forKey:NewsElement2]; if(NewsNumElements == 3) { [NewsItem setObject:NewsCurrentElement3 forKey:NewsElement3]; } [newsCategories addObject:[[NewsItem copy] autorelease]]; [NewsCurrentElement release]; [NewsCurrentElement1 release]; [NewsCurrentElement2 release]; if(NewsNumElements == 3) { [NewsCurrentElement3 release]; } [NewsItem release]; } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { //NSLog(@"found characters: %@", string); // save the characters for the current item... if ([NewsCurrentElement isEqualToString:NewsElement1]) { [NewsCurrentElement1 appendString:string]; } else if ([NewsCurrentElement isEqualToString:NewsElement2]) { [NewsCurrentElement2 appendString:string]; } else if (NewsNumElements == 3 && [NewsCurrentElement isEqualToString:NewsElement3]) { [NewsCurrentElement3 appendString:string]; } } - (void)dealloc { [super dealloc]; [newsCategories release]; [NewsItemType release]; [NewsElement1 release]; [NewsElement2 release]; [NewsElement3 release]; } When I create an instance of the class I do like so: NewsFeedParser *categoriesParser = [[NewsFeedParser alloc] init]; if(newsCat == 0) { categoriesParser.NewsItemType = @"article"; categoriesParser.NewsElement1 = @"category"; categoriesParser.NewsElement2 = @"catid"; } else { categoriesParser.NewsItemType = @"article"; categoriesParser.NewsElement1 = @"category"; categoriesParser.NewsElement2 = @"feedUrl"; } [categoriesParser parseXMLFileAtURL:feedUrl]; newsCategories = [[NSMutableArray alloc] initWithArray:categoriesParser.newsCategories copyItems:YES]; [self.tableView reloadData]; [categoriesParser release]; If I run the app with the leaks instrument, the leaks point to the [NSXMLNewsParser parse] call in the NewsFeedParser.m. Here is a screen shot of the Leaks instrument with the NSCFStrings leaking: http://img139.imageshack.us/img139/3997/leaks.png For the life of me I can't figure out where these leaks are coming from. Any help would be greatly appreciated.

    Read the article

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

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

    Read the article

  • [SOLVED] Iphone NSXMLParser NSCFString memory leak

    - by atticusalien
    I am building an app that parses an rss feed. In the app there are two different types of feeds with different names for the elements in the feed, so I have created an NSXMLParser NSObject that takes the name of the elements of each feed before parsing. Here is my code: NewsFeedParser.h #import @interface NewsFeedParser : NSObject { NSInteger NewsSelectedCategory; NSXMLParser *NSXMLNewsParser; NSMutableArray *newsCategories; NSMutableDictionary *NewsItem; NSMutableString *NewsCurrentElement, *NewsCurrentElement1, *NewsCurrentElement2, *NewsCurrentElement3; NSString *NewsItemType, *NewsElement1, *NewsElement2, *NewsElement3; NSInteger NewsNumElements; } - (void) parseXMLFileAtURL:(NSString *)URL; @property(nonatomic, retain) NSString *NewsItemType; @property(nonatomic, retain) NSString *NewsElement1; @property(nonatomic, retain) NSString *NewsElement2; @property(nonatomic, retain) NSString *NewsElement3; @property(nonatomic, retain) NSMutableArray *newsCategories; @property(assign, nonatomic) NSInteger NewsNumElements; @end NewsFeedParser.m #import "NewsFeedParser.h" @implementation NewsFeedParser @synthesize NewsItemType; @synthesize NewsElement1; @synthesize NewsElement2; @synthesize NewsElement3; @synthesize newsCategories; @synthesize NewsNumElements; - (void)parserDidStartDocument:(NSXMLParser *)parser{ } - (void)parseXMLFileAtURL:(NSString *)URL { newsCategories = [[NSMutableArray alloc] init]; URL = [URL stringByReplacingOccurrencesOfString:@" " withString:@""]; URL = [URL stringByReplacingOccurrencesOfString:@"\n" withString:@""]; URL = [URL stringByReplacingOccurrencesOfString:@" " withString:@""]; //you must then convert the path to a proper NSURL or it won't work NSURL *xmlURL = [NSURL URLWithString:URL]; // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error // this may be necessary only for the toolchain [[NSURLCache sharedURLCache] setMemoryCapacity:0]; [[NSURLCache sharedURLCache] setDiskCapacity:0]; NSXMLNewsParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks. [NSXMLNewsParser setDelegate:self]; // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser. [NSXMLNewsParser setShouldProcessNamespaces:NO]; [NSXMLNewsParser setShouldReportNamespacePrefixes:NO]; [NSXMLNewsParser setShouldResolveExternalEntities:NO]; [NSXMLNewsParser parse]; [NSXMLNewsParser release]; } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]]; NSLog(@"error parsing XML: %@", errorString); UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [errorAlert show]; [errorAlert release]; [errorString release]; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NewsCurrentElement = [elementName copy]; if ([elementName isEqualToString:NewsItemType]) { // clear out our story item caches... NewsItem = [[NSMutableDictionary alloc] init]; NewsCurrentElement1 = [[NSMutableString alloc] init]; NewsCurrentElement2 = [[NSMutableString alloc] init]; if(NewsNumElements == 3) { NewsCurrentElement3 = [[NSMutableString alloc] init]; } } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ if ([elementName isEqualToString:NewsItemType]) { // save values to an item, then store that item into the array... [NewsItem setObject:NewsCurrentElement1 forKey:NewsElement1]; [NewsItem setObject:NewsCurrentElement2 forKey:NewsElement2]; if(NewsNumElements == 3) { [NewsItem setObject:NewsCurrentElement3 forKey:NewsElement3]; } [newsCategories addObject:[[NewsItem copy] autorelease]]; [NewsCurrentElement release]; [NewsCurrentElement1 release]; [NewsCurrentElement2 release]; if(NewsNumElements == 3) { [NewsCurrentElement3 release]; } [NewsItem release]; } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { //NSLog(@"found characters: %@", string); // save the characters for the current item... if ([NewsCurrentElement isEqualToString:NewsElement1]) { [NewsCurrentElement1 appendString:string]; } else if ([NewsCurrentElement isEqualToString:NewsElement2]) { [NewsCurrentElement2 appendString:string]; } else if (NewsNumElements == 3 && [NewsCurrentElement isEqualToString:NewsElement3]) { [NewsCurrentElement3 appendString:string]; } } - (void)dealloc { [super dealloc]; [newsCategories release]; [NewsItemType release]; [NewsElement1 release]; [NewsElement2 release]; [NewsElement3 release]; } When I create an instance of the class I do like so: NewsFeedParser *categoriesParser = [[NewsFeedParser alloc] init]; if(newsCat == 0) { categoriesParser.NewsItemType = @"article"; categoriesParser.NewsElement1 = @"category"; categoriesParser.NewsElement2 = @"catid"; } else { categoriesParser.NewsItemType = @"article"; categoriesParser.NewsElement1 = @"category"; categoriesParser.NewsElement2 = @"feedUrl"; } [categoriesParser parseXMLFileAtURL:feedUrl]; newsCategories = [[NSMutableArray alloc] initWithArray:categoriesParser.newsCategories copyItems:YES]; [self.tableView reloadData]; [categoriesParser release]; If I run the app with the leaks instrument, the leaks point to the [NSXMLNewsParser parse] call in the NewsFeedParser.m. Here is a screen shot of the Leaks instrument with the NSCFStrings leaking: http://img139.imageshack.us/img139/3997/leaks.png For the life of me I can't figure out where these leaks are coming from. Any help would be greatly appreciated.

    Read the article

  • NSOutlineView not refreshing when objects added to managed object context from NSOperations

    - by John Gallagher
    Background Cocoa app using core data Two processes - daemon and a main UI Daemon constantly writing to a data store UI process reads from same data store NSOutlineView in UI is bound to an NSTreeController which is bound to Application with key path of delegate.interpretedMOC What I want When the UI is activated, the outline view should update with the latest data inserted by the daemon. The Problem Main Thread Approach I fetch all the entities I'm interested in, then iterate over them, doing refreshObject:mergeChanges:YES. This works OK - the items get refreshed correctly. However, this is all running on the main thread, so the UI locks up for 10-20 seconds whilst it refreshes. Fine, so let's move these refreshes to NSOperations that run in the background instead. NSOperation Multithreaded Approach As soon as I move the refreshObject:mergeChanges: call into an NSOperation, the refresh no longer works. When I add logging messages, it's clear that the new objects are loaded in by the NSOperation subclass and refreshed. Not only that, but they are What I've tried I've messed around with this for 2 days solid and tried everything I can think of. Passing objectIDs to the NSOperation to refresh instead of an entity name. Resetting the interpretedMOC at various points - after the data refresh and before the outline view reload. I'd subclassed NSOutlineView. I discarded my subclass and set the view back to being an instance of NSOutlineView, just in case there was any funny goings on here. Added a rearrangeObjects call to the NSTreeController before reloading the NSOutlineView data. Made sure I had set the staleness interval to 0 on all managed object contexts I was using. I've got a feeling this problem is somehow related to caching core data objects in memory. But I've totally exhausted all my ideas on how I get this to work. I'd be eternally grateful of any ideas anyone else has. Code Main Thread Approach // In App Delegate -(void)applicationDidBecomeActive:(NSNotification *)notification { // Delay to allow time for the daemon to save [self performSelector:@selector(refreshTrainingEntriesAndGroups) withObject:nil afterDelay:3]; } -(void)refreshTrainingEntriesAndGroups { NSSet *allTrainingGroups = [[[NSApp delegate] interpretedMOC] fetchAllObjectsForEntityName:kTrainingGroup]; for(JGTrainingGroup *thisTrainingGroup in allTrainingGroups) [interpretedMOC refreshObject:thisTrainingGroup mergeChanges:YES]; NSError *saveError = nil; [interpretedMOC save:&saveError]; [windowController performSelectorOnMainThread:@selector(refreshTrainingView) withObject:nil waitUntilDone:YES]; } // In window controller class -(void)refreshTrainingView { [trainingViewTreeController rearrangeObjects]; // Didn't really expect this to have any effect. And it didn't. [trainingView reloadData]; } NSOperation Multithreaded Approach // In App Delegate -(void)refreshTrainingEntriesAndGroups { JGRefreshEntityOperation *trainingGroupRefresh = [[JGRefreshEntityOperation alloc] initWithEntityName:kTrainingGroup]; NSOperationQueue *refreshQueue = [[NSOperationQueue alloc] init]; [refreshQueue setMaxConcurrentOperationCount:1]; [refreshQueue addOperation:trainingGroupRefresh]; while ([[refreshQueue operations] count] > 0) { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]]; [windowController performSelectorOnMainThread:@selector(refreshTrainingView) withObject:nil waitUntilDone:YES]; } // JGRefreshEntityOperation.m @implementation JGRefreshEntityOperation @synthesize started; @synthesize executing; @synthesize paused; @synthesize finished; -(void)main { [self startOperation]; NSSet *allEntities = [imoc fetchAllObjectsForEntityName:entityName]; for(id thisEntity in allEntities) [imoc refreshObject:thisEntity mergeChanges:YES]; [self finishOperation]; } -(void)startOperation { [self willChangeValueForKey:@"isExecuting"]; [self willChangeValueForKey:@"isStarted"]; [self setStarted:YES]; [self setExecuting:YES]; [self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isStarted"]; imoc = [[NSManagedObjectContext alloc] init]; [imoc setStalenessInterval:0]; [imoc setUndoManager:nil]; [imoc setPersistentStoreCoordinator:[[NSApp delegate] interpretedPSC]]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:imoc]; } -(void)finishOperation { saveError = nil; [imoc save:&saveError]; if (saveError) { NSLog(@"Error saving. %@", saveError); } imoc = nil; [self willChangeValueForKey:@"isExecuting"]; [self willChangeValueForKey:@"isFinished"]; [self setExecuting:NO]; [self setFinished:YES]; [self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isFinished"]; } -(void)mergeChanges:(NSNotification *)notification { NSManagedObjectContext *mainContext = [[NSApp delegate] interpretedMOC]; [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES]; } -(id)initWithEntityName:(NSString *)entityName_ { [super init]; [self setStarted:false]; [self setExecuting:false]; [self setPaused:false]; [self setFinished:false]; [NSThread setThreadPriority:0.0]; entityName = entityName_; return self; } @end // JGRefreshEntityOperation.h @interface JGRefreshEntityOperation : NSOperation { NSString *entityName; NSManagedObjectContext *imoc; NSError *saveError; BOOL started; BOOL executing; BOOL paused; BOOL finished; } @property(readwrite, getter=isStarted) BOOL started; @property(readwrite, getter=isPaused) BOOL paused; @property(readwrite, getter=isExecuting) BOOL executing; @property(readwrite, getter=isFinished) BOOL finished; -(void)startOperation; -(void)finishOperation; -(id)initWithEntityName:(NSString *)entityName_; -(void)mergeChanges:(NSNotification *)notification; @end

    Read the article

  • problem in adding image to the UIButton.

    - by monish
    Hi friends, I got an another problem in my application and I am wasting so much of time on that. Does pls anyone can help with this problem. Actually I had an Event and I should give rating for that event for that I wrote the code as: In CellForRowAtIndexPath......I had the code as: - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MasterViewIdentifier"]; //UITableViewCell *cell = nil; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"MasterViewIdentifier"] autorelease]; cell.selectionStyle = UITableViewCellSelectionStyleNone; UIView* elementView = [[UIView alloc] initWithFrame:CGRectMake(20,170,320,280)]; elementView.tag = 0; elementView.backgroundColor=[UIColor clearColor]; [cell.contentView addSubview:elementView]; [elementView release]; } UIView* elementView = [cell.contentView viewWithTag:0]; elementView.backgroundColor=[UIColor clearColor]; for(UIView* subView in elementView.subviews) { [subView removeFromSuperview]; } if(indexPath.section == 8) { UIImage *whiteImg = [UIImage imageNamed:@"white_star.png"] ; UIImage *yellowImg = [UIImage imageNamed:@"yellow_Star.png"] ; UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(159, 15, 25, 20)]; [button1 addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; button1.tag = 1; UIButton *button2 = [[UIButton alloc]initWithFrame:CGRectMake(185, 15, 25, 20)]; [button2 addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; button2.tag = 2; UIButton *button3 = [[UIButton alloc]initWithFrame:CGRectMake(211, 15, 25, 20)]; [button3 addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; button3.tag = 3; UIButton *button4 = [[UIButton alloc]initWithFrame:CGRectMake(237, 15, 25, 20)]; [button4 addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; button4.tag = 4; UIButton *button5 = [[UIButton alloc]initWithFrame:CGRectMake(263, 15, 25, 20)]; [button5 addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; button5.tag = 5; if(event.eventRatings == 1) { [button1 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button2 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button3 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button4 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button5 setBackgroundImage:whiteImg forState:UIControlStateNormal]; } else if(event.eventRatings == 2) { [button1 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button2 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button3 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button4 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button5 setBackgroundImage:whiteImg forState:UIControlStateNormal]; } else if(event.eventRatings == 3) { [button1 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button2 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button3 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button4 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button5 setBackgroundImage:whiteImg forState:UIControlStateNormal]; } else if(event.eventRatings == 4) { [button1 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button2 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button3 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button4 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button5 setBackgroundImage:whiteImg forState:UIControlStateNormal]; } else if(event.eventRatings == 5) { [button1 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button2 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button3 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button4 setBackgroundImage:yellowImg forState:UIControlStateNormal]; [button5 setBackgroundImage:yellowImg forState:UIControlStateNormal]; } else { [button1 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button2 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button3 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button4 setBackgroundImage:whiteImg forState:UIControlStateNormal]; [button5 setBackgroundImage:whiteImg forState:UIControlStateNormal]; } [elementView addSubview:button1]; [button1 release]; [elementView addSubview:button2]; [button2 release]; [elementView addSubview:button3]; [button3 release]; [elementView addSubview:button4]; [button4 release]; [elementView addSubview:button5]; [button5 release]; if(isRightButton == YES) { button1.enabled = NO; button2.enabled = NO; button3.enabled = NO; button4.enabled = NO; button5.enabled = NO; } else if(isRightButton == NO) { button1.enabled = YES; button2.enabled = YES; button3.enabled = YES; button4.enabled = YES; button5.enabled = YES; } [elementView addSubview:ratingsTitleLabel]; cell.accessoryType = UITableViewCellAccessoryNone; } return cell; } And the action of the button is written as: -(void)buttonAction:(id)sender { rating = [sender tag]; printf("\n Ratig Value inside Button Action~~~~~~~~~~~~~~~~%d",rating); event.eventRatings = rating; [tableView reloadData]; } When I build the application in simlator of 3.1.2 O.S its working fine by displaying the star images. My porblem is when I build it in 3.1.2 O.S Device the images are not displaying.I checked the code for casesensitivity in file name and its gud but Im not gettig the images to display. Guys help me to solve this. Thank you, Monish Kumar.

    Read the article

  • Moving items from one tableView to another tableView with extra's

    - by Totumus Maximus
    Let's say I have 2 UITableViews next to eachother on an ipad in landscape-mode. Now I want to move multiple items from one tableView to the other. They are allowed to be inserted on the bottom of the other tableView. Both have multiSelection activated. Now the movement itself is no problem with normal cells. But in my program each cell has an object which contains the consolidationState of the cell. There are 4 states a cell can have: Basic, Holding, Parent, Child. Basic = an ordinary cell. Holding = a cell which contains multiple childs but which wont be shown in this state. Parent = a cell which contains multiple childs and are shown directly below this cell. Child = a cell created by the Parent cell. The object in each cell also has some array which contains its children. The object also holds a quantityValue, which is displayed on the cell itself. Now the movement gets tricky. Holding and Parent cells can't move at all. Basic cells can move freely. Child cells can move freely but based on how many Child cells are left in the Parent. The parent will change or be deleted all together. If a Parent cell has more then 1 Child cell left it will stay a Parent cell. Else the Parent has no or 1 Child cell left and is useless. It will then be deleted. The items that are moved will always be of the same state. They will all be Basic cells. This is how I programmed the movement: *First I determine which of the tableViews is the sender and which is the receiver. *Second I ask all indexPathsForSelectedRows and sort them from highest row to lowest. *Then I build the data to be transferred. This I do by looping through the selectedRows and ask their object from the sender's listOfItems. *When I saved all the data I need I delete all the items from the sender TableView. This is why I sorted the selectedRows so I can start at the highest indexPath.row and delete without screwing up the other indexPaths. *When I loop through the selectedRows I check whether I found a cell with state Basic or Child. *If its a Basic cell I do nothing and just delete the cell. (this works fine with all Basic Cells) *If its a Child cell I go and check it's Parent cell immidiately. Since all Child cells are directly below the Parent cell and no other the the Parent's Childs are below that Parent I can safely get the path of the selected Childcell and move upwards and find it's Parent cell. When this Parent cell is found (this will always happen, no exceptions) it has to change accordingly. *The Parent cell will either be deleted or the object inside will have its quantity and children reduced. *After the Parent cell has changed accordingly the Child cell is deleted similarly like the Basic cells *After the deletion of the cells the receiver tableView will build new indexPaths so the movedObjects will have a place to go. *I then insert the objects into the listOfItems of the receiver TableView. The code works in the following ways: Only Basic cells are moved. Basic cells and just 1 child for each parent is moved. A single Basic/Child cell is moved. The code doesn't work when: I select more then 1 or all childs of some parent cell. The problem happens somewhere into updating the parent cells. I'm staring blindly at the code now so maybe a fresh look will help fix things. Any help will be appreciated. Here is the method that should do the movement: -(void)moveSelectedItems { UITableView *senderTableView = //retrieves the table with the data here. UITableView *receiverTableView = //retrieves the table which gets the data here. NSArray *selectedRows = senderTableView.indexPathsForSelectedRows; //sort selected rows from lowest indexPath.row to highest selectedRows = [selectedRows sortedArrayUsingSelector:@selector(compare:)]; //build up target rows (all objects to be moved) NSMutableArray *targetRows = [[NSMutableArray alloc] init]; for (int i = 0; i<selectedRows.count; i++) { NSIndexPath *path = [selectedRows objectAtIndex:i]; [targetRows addObject:[senderTableView.listOfItems objectAtIndex:path.row]]; } //delete rows at active for (int i = selectedRows.count-1; i >= 0; i--) { NSIndexPath *path = [selectedRows objectAtIndex:i]; //check what item you are deleting. act upon the status. Parent- and HoldingCells cant be selected so only check for basic and childs MyCellObject *item = [senderTableView.listOfItems objectAtIndex:path.row]; if (item.consolidatedState == ConsolidationTypeChild) { for (int j = path.row; j >= 0; j--) { MyCellObject *consolidatedItem = [senderTableView.listOfItems objectAtIndex:j]; if (consolidatedItem.consolidatedState == ConsolidationTypeParent) { //copy the consolidated item but with 1 less quantity MyCellObject *newItem = [consolidatedItem copyWithOneLessQuantity]; //creates a copy of the object with 1 less quantity. if (newItem.quantity > 1) { newItem.consolidatedState = ConsolidationTypeParent; [senderTableView.listOfItems replaceObjectAtIndex:j withObject:newItem]; } else if (newItem.quantity == 1) { newItem.consolidatedState = ConsolidationTypeBasic; [senderTableView.listOfItems removeObjectAtIndex:j]; MyCellObject *child = [senderTableView.listOfItems objectAtIndex:j+1]; child.consolidatedState = ConsolidationTypeBasic; [senderTableView.listOfItems replaceObjectAtIndex:j+1 withObject:child]; } else { [senderTableView.listOfItems removeObject:consolidatedItem]; } [senderTableView reloadData]; } } } [senderTableView.listOfItems removeObjectAtIndex:path.row]; } [senderTableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationTop]; //make new indexpaths for row animation NSMutableArray *newRows = [[NSMutableArray alloc] init]; for (int i = 0; i < targetRows.count; i++) { NSIndexPath *newPath = [NSIndexPath indexPathForRow:i+receiverTableView.listOfItems.count inSection:0]; [newRows addObject:newPath]; DLog(@"%i", i); //scroll to newest items [receiverTableView setContentOffset:CGPointMake(0, fmaxf(receiverTableView.contentSize.height - recieverTableView.frame.size.height, 0.0)) animated:YES]; } //add rows at target for (int i = 0; i < targetRows.count; i++) { MyCellObject *insertedItem = [targetRows objectAtIndex:i]; //all moved items will be brought into the standard (basic) consolidationType insertedItem.consolidatedState = ConsolidationTypeBasic; [receiverTableView.ListOfItems insertObject:insertedItem atIndex:receiverTableView.ListOfItems.count]; } [receiverTableView insertRowsAtIndexPaths:newRows withRowAnimation:UITableViewRowAnimationNone]; } If anyone has some fresh ideas of why the movement is bugging out let me know. If you feel like you need some extra information I'll be happy to add it. Again the problem is in the movement of ChildCells and updating the ParentCells properly. I could use some fresh looks and outsider ideas on this. Thanks in advance. *updated based on comments

    Read the article

  • Add UIView and UILabel to UICollectionViewCell. Then Segue based on clicked cell index

    - by JetSet
    I am new to collection views in Objective-C. Can anyone tell me why I can't see my UILabel embedded in the transparent UIView and the best way to resolve. I want to also segue from the cell to several various UIViewControllers based on the selected index cell. I am using GitHub project https://github.com/mayuur/MJParallaxCollectionView Overall, in MJRootViewController.m I wanted to add a UIView with a transparency and a UILabel with details of the cell from a array. MJCollectionViewCell.h // MJCollectionViewCell.h // RCCPeakableImageSample // // Created by Mayur on 4/1/14. // Copyright (c) 2014 RCCBox. All rights reserved. // #import <UIKit/UIKit.h> #define IMAGE_HEIGHT 200 #define IMAGE_OFFSET_SPEED 25 @interface MJCollectionViewCell : UICollectionViewCell /* image used in the cell which will be having the parallax effect */ @property (nonatomic, strong, readwrite) UIImage *image; /* Image will always animate according to the imageOffset provided. Higher the value means higher offset for the image */ @property (nonatomic, assign, readwrite) CGPoint imageOffset; //@property (nonatomic,readwrite) UILabel *textLabel; @property (weak, nonatomic) IBOutlet UILabel *textLabel; @property (nonatomic,readwrite) NSString *text; @property(nonatomic,readwrite) CGFloat x,y,width,height; @property (nonatomic,readwrite) NSInteger lineSpacing; @property (nonatomic, strong) IBOutlet UIView* overlayView; @end MJCollectionViewCell.m // // MJCollectionViewCell.m // RCCPeakableImageSample // // Created by Mayur on 4/1/14. // Copyright (c) 2014 RCCBox. All rights reserved. // #import "MJCollectionViewCell.h" @interface MJCollectionViewCell() @property (nonatomic, strong, readwrite) UIImageView *MJImageView; @end @implementation MJCollectionViewCell - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) [self setupImageView]; return self; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) [self setupImageView]; return self; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ #pragma mark - Setup Method - (void)setupImageView { // Clip subviews self.clipsToBounds = YES; // Add image subview self.MJImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, IMAGE_HEIGHT)]; self.MJImageView.backgroundColor = [UIColor redColor]; self.MJImageView.contentMode = UIViewContentModeScaleAspectFill; self.MJImageView.clipsToBounds = NO; [self addSubview:self.MJImageView]; } # pragma mark - Setters - (void)setImage:(UIImage *)image { // Store image self.MJImageView.image = image; // Update padding [self setImageOffset:self.imageOffset]; } - (void)setImageOffset:(CGPoint)imageOffset { // Store padding value _imageOffset = imageOffset; // Grow image view CGRect frame = self.MJImageView.bounds; CGRect offsetFrame = CGRectOffset(frame, _imageOffset.x, _imageOffset.y); self.MJImageView.frame = offsetFrame; } - (void)setText:(NSString *)text{ _text=text; if (!self.textLabel) { CGFloat realH=self.height*2/3-self.lineSpacing; CGFloat latoA=realH/3; // self.textLabel=[[UILabel alloc] initWithFrame:CGRectMake(10,latoA/2, self.width-20, realH)]; self.textLabel.layer.anchorPoint=CGPointMake(.5, .5); self.textLabel.font=[UIFont fontWithName:@"HelveticaNeue-ultralight" size:38]; self.textLabel.numberOfLines=3; self.textLabel.textColor=[UIColor whiteColor]; self.textLabel.shadowColor=[UIColor blackColor]; self.textLabel.shadowOffset=CGSizeMake(1, 1); self.textLabel.transform=CGAffineTransformMakeRotation(-(asin(latoA/(sqrt(self.width*self.width+latoA*latoA))))); [self addSubview:self.textLabel]; } self.textLabel.text=text; } @end MJViewController.h // // MJViewController.h // ParallaxImages // // Created by Mayur on 4/1/14. // Copyright (c) 2014 sky. All rights reserved. // #import <UIKit/UIKit.h> @interface MJRootViewController : UIViewController{ NSInteger choosed; } @end MJViewController.m // // MJViewController.m // ParallaxImages // // Created by Mayur on 4/1/14. // Copyright (c) 2014 sky. All rights reserved. // #import "MJRootViewController.h" #import "MJCollectionViewCell.h" @interface MJRootViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate> @property (weak, nonatomic) IBOutlet UICollectionView *parallaxCollectionView; @property (nonatomic, strong) NSMutableArray* images; @end @implementation MJRootViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //self.navigationController.navigationBarHidden=YES; // Fill image array with images NSUInteger index; for (index = 0; index < 14; ++index) { // Setup image name NSString *name = [NSString stringWithFormat:@"image%03ld.jpg", (unsigned long)index]; if(!self.images) self.images = [NSMutableArray arrayWithCapacity:0]; [self.images addObject:name]; } [self.parallaxCollectionView reloadData]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - UICollectionViewDatasource Methods - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return self.images.count; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { MJCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MJCell" forIndexPath:indexPath]; //get image name and assign NSString* imageName = [self.images objectAtIndex:indexPath.item]; cell.image = [UIImage imageNamed:imageName]; //set offset accordingly CGFloat yOffset = ((self.parallaxCollectionView.contentOffset.y - cell.frame.origin.y) / IMAGE_HEIGHT) * IMAGE_OFFSET_SPEED; cell.imageOffset = CGPointMake(0.0f, yOffset); NSString *text; NSInteger index=choosed>=0 ? choosed : indexPath.row%5; switch (index) { case 0: text=@"I am the home cell..."; break; case 1: text=@"I am next..."; break; case 2: text=@"Cell 3..."; break; case 3: text=@"Cell 4..."; break; case 4: text=@"The last cell"; break; default: break; } cell.text=text; cell.overlayView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.4f]; //cell.textLabel.text = @"Label showing"; cell.textLabel.font = [UIFont boldSystemFontOfSize:22.0f]; cell.textLabel.textColor = [UIColor whiteColor]; //This is another attempt to display the label by using tags. //UILabel* label = (UILabel*)[cell viewWithTag:1]; //label.text = @"Label works"; return cell; } #pragma mark - UIScrollViewdelegate methods - (void)scrollViewDidScroll:(UIScrollView *)scrollView { for(MJCollectionViewCell *view in self.parallaxCollectionView.visibleCells) { CGFloat yOffset = ((self.parallaxCollectionView.contentOffset.y - view.frame.origin.y) / IMAGE_HEIGHT) * IMAGE_OFFSET_SPEED; view.imageOffset = CGPointMake(0.0f, yOffset); } } @end

    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

  • Received memory warning. Level=2, Program received signal: “0”.

    - by sabby
    Hi friends I am getting images from webservice and loading these images in table view.But when i continue to scroll the program receives memory warning level1,level2 and then app exits with status 0.That happens only in device not in simulator. Here is my code which i am putting please help me out. - (void)viewDidLoad { [super viewDidLoad]; UIButton *infoButton = [[UIButton alloc] initWithFrame:CGRectMake(0, -4, 62, 30)]; [infoButton setBackgroundImage:[UIImage imageNamed: @"back.png"] forState:UIControlStateNormal]; [infoButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *customBarButtomItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton]; self.navigationItem.leftBarButtonItem = customBarButtomItem; [customBarButtomItem release]; [infoButton release]; UIButton *homeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 62, 30)]; [homeButton setBackgroundImage:[UIImage imageNamed: @"home.png"] forState:UIControlStateNormal]; [homeButton.titleLabel setFont:[UIFont systemFontOfSize:11]]; //[homeButton setTitle:@"UPLOAD" forState:UIControlStateNormal]; [homeButton addTarget:self action:@selector(homeButtonClicked) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *rightBarButtom = [[UIBarButtonItem alloc] initWithCustomView:homeButton]; self.navigationItem.rightBarButtonItem = rightBarButtom; [rightBarButtom release]; [homeButton release]; sellerTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 416) style:UITableViewStylePlain]; sellerTableView.delegate=self; sellerTableView.dataSource=self; sellerTableView.backgroundColor=[UIColor clearColor]; sellerTableView.scrollEnabled=YES; //table.separatorColor=[UIColor grayColor]; //table.separatorColor=[UIColor whiteColor]; //[[table layer]setRoundingMode:NSNumberFormatterRoundDown]; [[sellerTableView layer]setBorderColor:[[UIColor darkGrayColor]CGColor]]; [[sellerTableView layer]setBorderWidth:2]; //[[productTable layer]setCornerRadius:10.3F]; [self.view addSubview:sellerTableView]; appDel = (SnapItAppAppDelegate*)[[UIApplication sharedApplication] delegate]; } -(void)viewWillAppear:(BOOL)animated { spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; spinner.center = self.view.center; [self.view addSubview:spinner]; [spinner startAnimating]; [[SnapItParsing sharedInstance]assignSender:self]; [[SnapItParsing sharedInstance]startParsingForShowProducts:appDel.userIdString]; [sellerTableView reloadData]; } -(void)showProducts:(NSMutableArray*)proArray { if (spinner) { [spinner stopAnimating]; [spinner removeFromSuperview]; [spinner release]; spinner = nil; } if ([[[proArray objectAtIndex:1]objectForKey:@"Success"]isEqualToString:@"True"]) { //[self.navigationController popViewControllerAnimated:YES]; //self.view.alpha=.12; if (productInfoArray) { [productInfoArray release]; } productInfoArray=[[NSMutableArray alloc]init]; for (int i=2; i<[proArray count]; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [productInfoArray addObject:[proArray objectAtIndex:i]]; NSLog(@"data fetch array is====> /n%@",productInfoArray); [pool release]; } } } #pragma mark (tableview methods) - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 100; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { //return [resultarray count]; return [productInfoArray count]; } -(void)loadImagesInBackground:(NSNumber *)index{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSMutableDictionary *frame = [[productInfoArray objectAtIndex:[index intValue]] retain]; //NSLog(@"frame value ==>%@",[[frame objectForKey:@"Image"]length]); NSString *frameImagePath = [NSString stringWithFormat:@"http://apple.com/snapit/products/%@",[frame objectForKey:@"Image"]]; NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:frameImagePath]]; NSLog(@"FRAME IMAGE%d",[[frame valueForKey:@"Image" ]length]); if([[frame valueForKey:@"Image"] length] == 0){ NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; [frame setObject:image forKey:@"friendImage"]; [imagePath release]; //[image release]; } else { //NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:frameImagePath]]; NSLog(@"image data length ==>%d",[imageData length]); if([imageData length] == 0){ NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; [frame setObject:image forKey:@"friendImage"]; [imagePath release]; //[image release]; } else { //UIImage *image = [[UIImage alloc] initWithData:imageData]; UIImage *image = [UIImage imageWithData:imageData]; [frame setObject:image forKey:@"friendImage"]; //[image release]; } } [frame release]; frame = nil; [self performSelectorOnMainThread:@selector(reloadTable:) withObject:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[index intValue] inSection:0]] waitUntilDone:NO]; [pool release]; } -(void)reloadTable:(NSArray *)array{ NSLog(@"array ==>%@",array); [sellerTableView reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *celltype=@"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celltype]; for (UIView *view in cell.contentView.subviews) { [view removeFromSuperview]; } if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] autorelease]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.backgroundColor=[UIColor clearColor]; //cell.textLabel.text=[[resultarray objectAtIndex:indexPath.row] valueForKey:@"Service"]; /*UIImage *indicatorImage = [UIImage imageNamed:@"indicator.png"]; cell.accessoryView = [[[UIImageView alloc] initWithImage:indicatorImage] autorelease];*/ /*NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector() object:nil]; [thread setStackSize:44]; [thread start];*/ cell.backgroundView=[[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cell.png"]]autorelease]; // [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back.png"]] autorelease]; cell.selectionStyle=UITableViewCellSelectionStyleNone; } UIImageView *imageView= [[UIImageView alloc] initWithFrame:CGRectMake(19, 15, 75, 68)]; imageView.contentMode = UIViewContentModeScaleToFill; // @synchronized(self) //{ NSMutableDictionary *dict = [productInfoArray objectAtIndex:indexPath.row]; if([dict objectForKey:@"friendImage"] == nil){ imageView.backgroundColor = [UIColor clearColor]; if ([dict objectForKey:@"isThreadLaunched"] == nil) { [NSThread detachNewThreadSelector:@selector(loadImagesInBackground:) toTarget:self withObject:[NSNumber numberWithInt:indexPath.row]]; [dict setObject:@"Yes" forKey:@"isThreadLaunched"]; } }else { imageView.image =[dict objectForKey:@"friendImage"]; } //NSString *imagePath = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"no_image.png"]; //imageView.layer.cornerRadius = 20.0;//vk //imageView.image=[UIImage imageWithContentsOfFile:imagePath]; //imageView.layer.masksToBounds = YES; //imageView.layer.borderColor = [UIColor darkGrayColor].CGColor; //imageView.layer.borderWidth = 1.0;//vk //imageView.layer.cornerRadius=7.2f; [cell.contentView addSubview:imageView]; //[imagePath release]; [imageView release]; imageView = nil; //} UILabel *productCodeLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 7, 60,20 )]; productCodeLabel.textColor = [UIColor whiteColor]; productCodeLabel.backgroundColor=[UIColor clearColor]; productCodeLabel.text=[NSString stringWithFormat:@"%@",@"Code"]; [cell.contentView addSubview:productCodeLabel]; [productCodeLabel release]; UILabel *CodeValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 7, 140,20 )]; CodeValueLabel.textColor = [UIColor whiteColor]; CodeValueLabel.backgroundColor=[UIColor clearColor]; CodeValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"ID"]]; [cell.contentView addSubview:CodeValueLabel]; [CodeValueLabel release]; UILabel *productNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 35, 60,20 )]; productNameLabel.textColor = [UIColor whiteColor]; productNameLabel.backgroundColor=[UIColor clearColor]; productNameLabel.text=[NSString stringWithFormat:@"%@",@"Name"]; [cell.contentView addSubview:productNameLabel]; [productNameLabel release]; UILabel *NameValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 35, 140,20 )]; NameValueLabel.textColor = [UIColor whiteColor]; NameValueLabel.backgroundColor=[UIColor clearColor]; NameValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"Title"]]; [cell.contentView addSubview:NameValueLabel]; [NameValueLabel release]; UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 68, 60,20 )]; dateLabel.textColor = [UIColor whiteColor]; dateLabel.backgroundColor=[UIColor clearColor]; dateLabel.text=[NSString stringWithFormat:@"%@",@"Date"]; [cell.contentView addSubview:dateLabel]; [dateLabel release]; UILabel *dateValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 68, 140,20 )]; dateValueLabel.textColor = [UIColor whiteColor]; dateValueLabel.backgroundColor=[UIColor clearColor]; dateValueLabel.text=[NSString stringWithFormat:@"%@",[[productInfoArray objectAtIndex:indexPath.row]valueForKey:@"PostedDate"]]; dateValueLabel.font=[UIFont systemFontOfSize:14]; dateValueLabel.numberOfLines=3; dateValueLabel.adjustsFontSizeToFitWidth=YES; [dateValueLabel setLineBreakMode:UILineBreakModeCharacterWrap]; [cell.contentView addSubview:dateValueLabel]; [dateValueLabel release]; } Please-2 help me out ,where i am doing mistake.....

    Read the article

  • NSXMLParser and Geonames

    - by Xcoder
    I'm trying to parse a call from Geonames with NSXMLParser in the iPhone SDK. I've used this before but for some reason I'm getting an empty dictionary back even though I get results back in a web browser. Can someone please point out what I may be doing wrong. Below is the code I'm using and the results that comes back pasting it in a browser. Thanks in advance #pragma mark - #pragma mark - Parcer Services -(void)beginLoadingFeed{ //[self startLoadingWithMessage:@"Loading Results...."]; NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadFeed) object:nil]; [operationQueue addOperation:operation]; [operation release]; } - (void)loadFeed{ NSString *path = [NSString stringWithFormat:@"http://ws.geonames.org/postalCodeSearch?placename=%@&long&maxRows=20",self.location]; [Logger log:@"Geonames Query: %@",path]; [self parseXMLFileAtURL:path]; [self performSelectorOnMainThread:@selector(didfinishedLoadingFeed) withObject:nil waitUntilDone:YES]; } -(void)didfinishedLoadingFeed{ } - (void)parserDidStartDocument:(NSXMLParser *)parser{ [Logger log:@"found file and started parsing"]; } //Called when the parser runs into an open tag (<tag>) - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ([elementName isEqualToString:@"code"]) { currentResult = [NSMutableDictionary dictionary]; } else { currentElement = [elementName copy]; } } //This is just to resolve random HTML entities - (NSData *)parser:(NSXMLParser *)parser resolveExternalEntityName:(NSString *)entityName systemID:(NSString *)systemID { return [entityName dataUsingEncoding:NSASCIIStringEncoding]; } - (void)parseXMLFileAtURL:(NSString *)URL{ self.results = [[[NSMutableArray alloc] init] autorelease]; NSURL *xmlURL = [NSURL URLWithString:URL]; NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; [parser setDelegate:self]; [parser parse]; [parser autorelease]; } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSString * errorString = [NSString stringWithFormat:@"Unable to connect to web site (Error code %i )", [parseError code]]; [Logger log:@"error parsing : %@", errorString]; [self stopLoadingView]; [self showMessage:@"Error loading content" withTitle:@"Error Loading"]; } /*** Called when the parser runs into a close tag (</tag>). If it is the Result tag that is closing, we should add the currentResult to the array, and then forget about it ***/ - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"code"]) { [self.results addObject:currentResult]; currentResult = nil; } } - (void)parserDidEndDocument:(NSXMLParser *)parser { [Logger log:@"all done!"]; [Logger log:@"results array has %d items", [self.results count]]; [Logger log:@"Results:%@",results]; [theTableView reloadData]; [self stopLoadingView]; } Below is the result that comes back in a browser using the same call above when doing the search for the term "boston": <?xml version="1.0" encoding="UTF-8" standalone="no"?> <geonames> <totalResultsCount>2808</totalResultsCount> <code> <postalcode>02101</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.370567</lat> <lng>-71.026964</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02108</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.357603</lat> <lng>-71.068432</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02109</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.360027</lat> <lng>-71.054495</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02110</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.357636</lat> <lng>-71.051417</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02111</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.350348</lat> <lng>-71.0629</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02114</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.361111</lat> <lng>-71.06823</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02115</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.342706</lat> <lng>-71.092215</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02116</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.349201</lat> <lng>-71.076798</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02118</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.336162</lat> <lng>-71.072854</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02128</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.364197</lat> <lng>-71.025694</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02199</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.347873</lat> <lng>-71.082543</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02210</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.348921</lat> <lng>-71.046511</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02215</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.347088</lat> <lng>-71.102689</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>22713</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>38.538241</lat> <lng>-78.142285</lng> <adminCode1>VA</adminCode1> <adminName1>Virginia</adminName1> <adminCode2>047</adminCode2> <adminName2>Culpeper</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>24592</postalcode> <name>South Boston</name> <countryCode>US</countryCode> <lat>36.696335</lat> <lng>-78.918829</lng> <adminCode1>VA</adminCode1> <adminName1>Virginia</adminName1> <adminCode2>083</adminCode2> <adminName2>Halifax</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02102</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.338947</lat> <lng>-70.919635</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02103</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.338947</lat> <lng>-70.919635</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02104</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.338947</lat> <lng>-70.919635</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02105</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.338947</lat> <lng>-70.919635</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> <code> <postalcode>02106</postalcode> <name>Boston</name> <countryCode>US</countryCode> <lat>42.354318</lat> <lng>-71.073449</lng> <adminCode1>MA</adminCode1> <adminName1>Massachusetts</adminName1> <adminCode2>025</adminCode2> <adminName2>Suffolk</adminName2> <adminCode3/> <adminName3/> </code> </geonames>

    Read the article

< Previous Page | 3 4 5 6 7