Search Results

Search found 295 results on 12 pages for 'uitableviewcontroller'.

Page 12/12 | < Previous Page | 8 9 10 11 12 

  • Code to show UIPickerview under clicked UITextField

    - by Chris F
    I thought I'd share a code snippet where I show a UIPickerView when you click a UITextField. The code uses a UIPickerView, but there's no reason to use a different view controller, like a UITableViewController that uses a table instead of a picker. Just create a single-view project with a nib, and add a UITextField to the view and make you connections in IB. // .h file #import @interface MyPickerViewViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate> - (IBAction)dismissPickerView:(id)sender; @end // .m file #import "MyPickerViewViewController.h" @interface MyPickerViewViewController () { UIPickerView *_pv; NSArray *_array; IBOutlet __weak UITextField *_tf; BOOL _pickerViewShown; } @end @implementation MyPickerViewViewController - (void)viewDidLoad { [super viewDidLoad]; _pickerViewShown = NO; _array = [NSArray arrayWithObjects:@"One", @"Two", @"Three", @"Four", nil]; _pv = [[UIPickerView alloc] initWithFrame:CGRectZero]; _pv.showsSelectionIndicator = YES; _pv.dataSource = self; _pv.delegate = self; _tf.delegate = self; _tf.inputView = _pv; } - (IBAction)dismissPickerView:(id)sender { [_pv removeFromSuperview]; [_tf.inputView removeFromSuperview]; [_tf resignFirstResponder]; _pickerViewShown = NO; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { if (!_pickerViewShown) { [self setRectForPickerViewRelativeToTextField:textField]; [self.view addSubview:_tf.inputView]; _pickerViewShown = YES; } else { [self dismissPickerView:self]; } return NO; } - (void)setRectForPickerViewRelativeToTextField:(UITextField*)textField { CGFloat xPos = textField.frame.origin.x; CGFloat yPos = textField.frame.origin.y; CGFloat width = textField.frame.size.width; CGFloat height = textField.frame.size.height; CGFloat pvHeight = _pv.frame.size.height; CGRect pvRect = CGRectMake(xPos, yPos+height, width, pvHeight); _pv.frame = pvRect; } - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [_array objectAtIndex:row]; } - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 1; } - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { return _array.count; } - (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { _tf.text = [_array objectAtIndex:row]; [self dismissPickerView:self]; } @end

    Read the article

  • I want to get the value from one class (SearchTableViewController.m) to another class (HistoryTableV

    - by ahmet732
    #import <UIKit/UIKit.h> @class SearchDetailViewController; @interface SearchTableViewController : UITableViewController <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>{ IBOutlet UITableView *myTableView; NSMutableArray *tableData;//will be storing data that will be displayed in table. //Search array den buna aktarma yapcaz ilerde görceksin. NSMutableArray *searchedData;//will be storing data matching with the search string UISearchBar *sBar;//search bar NSMutableArray *searchArray; // It holds the medicines that are shown in tableview SearchDetailViewController * searchDetailViewController; NSMutableArray *deneme; } @property(nonatomic,retain)UISearchBar *sBar; @property(nonatomic,retain)IBOutlet UITableView *myTableView; @property(nonatomic,retain)NSMutableArray *tableData; @property(nonatomic,retain)NSMutableArray *searchedData; @property (nonatomic, retain) NSMutableArray *searchArray; @property (nonatomic, retain) SearchDetailViewController *searchDetailViewController; @property (nonatomic, copy) NSMutableArray *deneme; @end SearchTableViewController.m - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. // AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil]; // [self.navigationController pushViewController:anotherViewController]; // [anotherViewController release]; **deneme= [[NSMutableArray alloc]init]; deneme=[tableData objectAtIndex:indexPath.row];** ****NSLog(@"my row = %@", deneme);**// I holded one of the selected cells here** HistoryTableViewController.m - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. // AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil]; // [self.navigationController pushViewController:anotherViewController]; // [anotherViewController release]; **SearchTableViewController *obj= [[SearchTableViewController alloc]init];** **NSLog(@"my 2nd row= %@", [obj deneme]); //it prints nil** } My project is TabBar. There are two buttons on it- Search and History. I want to display selected items in a table in History tab. But i can not bring the selected item from SearchTableViewController.m to the class (HistoryTableViewController.m) The problem is : I can hold one of the selected items in an array (named deneme)from table in SearchTableViewController.m but i can not take it to HistoryTableViewController.m. It prints nil in console screen.... If I can make it visible in History class, I display those selected items on table. Please help me !!!

    Read the article

  • UITableView: Handle cell selection in a mixed cell table view static and dynamic cells

    - by AlexR
    I am trying to mix dynamic and static cells in a grouped table view: I would like to get two sections with static cells at the top followed by a section of dynamic cells (please refer to the screenshot below). I have set the table view contents to static cells. Edit Based on AppleFreak's advice I have changed my code as follows: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell; if (indexPath.section <= 1) { // section <= 1 indicates static cells cell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; } else { // section > 1 indicates dynamic cells CellIdentifier = [NSString stringWithFormat:@"section%idynamic",indexPath.section]; cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; } return cell; } However, my app crashes with error message Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' for section 0 and row 0. The cell returned from cell = [super tableView:tableView cellForRowAtIndexPath:indexPath] for section 0 and row 0 is nil. What is wrong with my code? Could there be any problems with my outlets? I haven't set any outlets because I am subclassing UITableViewController and supposedly do not any outlets for tableview to be set (?). Any suggestions on how to better do it? Edit II I have recreated my scene in storyboard (please refer to my updated screen shot above) and rewritten the view controller in order to start from a new base. I have also read the description in Apple's forum as applefreak suggested. However, I run in my first problem with the method numberOfSectionsInTableView:tableView, in which I increment the number of static sections (two) by one. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [super numberOfSectionsInTableView:tableView] + 1 ; } The app crashed with the error message: Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 2 beyond bounds [0 .. 1]' Why is this code not working for me even though I followed Apple's and applefreak recommendations? It is possible that the tableView has changed a bit in iOS 6? Solution: I got this to work now using AppleFreaks code sample in his answer below. Thank you, AppleFreak! Edit III: Cell Selection: How can I handle cell selection in a mixed (dynamic and static cells) cell table view? When do I call super and when do I call self tableView? When I use [[super tableView] selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone] and try to check for the selected index paths with: UITableView *tableView = [super tableView]; if ( [[tableView indexPathForSelectedRow] isEqual:customGrowthIndexPath] ) { .. } I get an return value of nil. As I can't find the source of my error, I really would appreciate your help

    Read the article

  • UITableView: Mixing static and dynamic cells

    - by AlexR
    I am trying to mix dynamic and static cells in a grouped table view: I would like to get two sections with static cells at the top followed by a section of dynamic cells (please refer to the screenshot below). I have set the table view contents to static cells. I designed the static cells in Interface Builder and gave them identifiers related to their section and row: "section0static0", "section0static1", "section1static0" and "section1static1". I named the dynamic cell "section2dynamic". My delegate methods, in which I am trying to return the correct cell identifier (static or dynamic) are as follows: - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { switch (section) { case 0: return 2; break; case 1: return 2; break; case 2: return 0; break; default: break; } return 0; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @""; if (indexPath.section <= 1) CellIdentifier = [NSString stringWithFormat:@"section%istatic%i",indexPath.section,indexPath.row]; else CellIdentifier = [NSString stringWithFormat:@"section%idynamic",indexPath.section]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; return cell; } Edit Based on AppleFreak's advice I have changed my code as follows: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell; if (indexPath.section <= 1) { // section <= 1 indicates static cells cell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; } else { // section > 1 indicates dynamic cells CellIdentifier = [NSString stringWithFormat:@"section%idynamic",indexPath.section]; cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; } return cell; } However, my app crashes with error message Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' for section 0 and row 0. The cell returned from cell = [super tableView:tableView cellForRowAtIndexPath:indexPath] for section 0 and row 0 is nil. What is wrong with my code? Could there be any problems with my outlets? I haven't set any outlets because I am subclassing UITableViewController and supposedly do not any outlets for tableview to be set (?). Any suggestions on how to better do it?

    Read the article

  • Adding Insert Row in tableView

    - by user333624
    Hello everyone, I have a tableView that loads its data directly from a Core Data table with a NSFetchedResultsController. I'm not using an intermediate NSMutableArray to store the objects from the fetch results; I basically implemented inside my UITableViewController the protocol method numberOfRowsInSection and it returns the numberOfObjects inside a NSFetchedResultsSectionInfo. id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section]; and then I configure the cell content by implementing configureCell:atIndexPath and retrieving object info from the fetchedResultController but right now I have a generic configuration for any object (to avoid complications) cell.textLabel.text = @"categoria"; I also have a NavigationBar with a custom edit button at the right that loads my own selector called customSetEditing. What I'm trying to accomplish is to load an "Insert Cell" at the beginning of the tableView so when I tap it, it creates a new record. This last part is easy to implement the problem is that I dont's seem to be able to load the insert row or any row when I tap on the navigation bar edit button. this is the code for my customSetEditing: - (void) customSetEditing { [super setEditing:YES animated:YES]; [self.tableView setEditing:YES animated:YES]; [[self tableView] beginUpdates]; //[[self tableView] beginUpdates]; UIBarButtonItem *customDoneButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(customDone)]; [self.navigationItem.rightBarButtonItem release]; self.navigationItem.rightBarButtonItem = customDoneButtonItem; //[categoriasArray insertObject:[NSNull null] atIndex:0]; NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithObjects:[NSIndexPath indexPathForRow:0 inSection:0],nil ]; [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop]; //[indexPaths release]; [self.tableView reloadData];} Before adding the:[self.tableView reloadData]; I was getting an out of bounds error plus a program crash and although the program is not crashing it is not loading anything. I have seen many examples of similar situations in stackoverflow (by the way is an excellent forum with very helpful and nice people) none of the examples seems to work for me. Any ideas?

    Read the article

  • Issue Displaying/Hiding Views (Obj-C iPhone Programming)

    - by roswell
    All right all, So I've got a UITableView that is inited in applicationDidFinishLaunching like so: [self showForumList]; Said method does this: -(void)showForumList { ForumList *fl = [ForumList alloc]; [fl initWithNibName:@"ForumList" bundle:[NSBundle mainBundle]]; self.ForumList = fl; [window addSubview:[self.ForumList view]]; [fl release]; }where self.ForumList is previously defined in the interface as ForumList *ForumList;, etc. Now, in ForumList (itself an extension of UITableViewController obviously), I've got didSelectRowAtIndexPath: -- within it I have the following code: Forum *f = [Forum alloc]; NSArray *forums = [f getForumList]; NSDictionary *selectedForum = [forums objectAtIndex:[indexPath row]]; NSString *Url = [selectedForum objectForKey:@"url"]; NSString *Username = [selectedForum objectForKey:@"username"]; NSString *Password = [selectedForum objectForKey:@"password"]; NSLog(@"Identified press on forum %@ (%@/%@)", Url, Username, Password); [self.globalDelegate showForumListFromForumUsingUrl:Url username:Username password:Password]; [self.globalDelegate closeForumList]; NSLog(@"ForumListFromForum init"); Both of the NSLog calls in this function are executed and perform as they should. Now, here is where the issue starts. self.globalDelegate is defined as AppDelegate *globalDelegate; in the Interface specification in my header file. However, [self.globalDelegate showForumListFromForumUsingUrl:username:password] and and [self.globalDelegate closeForumList] are never actually called. They look like so: -(void)closeForumList { NSLog(@"Hiding forum list"); [[self.ForumList view] removeFromSuperview]; } -(void)showForumListFromForumUsingUrl:(NSString *)Url username:(NSString *)Username password:(NSString *)Password { NSLog(@"Showing forum list from forum"); ForumListFromForum *fl = [ForumListFromForum alloc]; [fl initWithNibName:@"ForumListFromForum" bundle:[NSBundle mainBundle]]; [fl initFromForumWithUrl:Url username:Username password:Password]; self.ForumListFromForum = fl; [window addSubview:[self.ForumListFromForum view]]; [fl release]; } The app does not respond to my press and neither of these NSLog calls are made. Any idea where I've gone wrong?

    Read the article

  • iPhone/Obj-C: Accessing a UIScrollView from a View displayed within it.

    - by Daniel I-S
    I'm writing a simple iPhone app which lets a user access a series of calculators. It consists of the following: UITableViewController (RootViewController), with the list of calculators. UIViewController + UIScrollView (UniversalScroller), which represents an empty scroll view - and has a 'displayedViewController' property. UIViewController (Calculators 1-9), each of which contains a view with controls that represents a particular calculator. Each calculator takes 3-5 values via UITextFields and UISliders, and has a 'calculate' button. They can potentially be taller than 460px(iPhone screen height). The idea is: User taps on a particular menu item in the RootViewController. This loads and inits UniversalScroller, ALSO loads and inits the UIViewcontroller for the particular calculator that was selected, sets the displayedViewController property of UniversalScroller to the newly loaded calculator UIViewcontroller, and pushes the UniversalScroller to the front. When the UniversalScroller hits its 'viewDidLoad' event, it sets its contentSize to the view frame size of its 'displayedViewController' object. It then adds the displayedViewController's view as a subview to itself, and sets its own title to equal that of the displayedViewController. It now displays the calculator, along with the correct title, in a scrollable form. Conceptually (and currently; this stuff has all been implemented already), this works great - I can design the calculators how I see fit, as tall as they end up being, and they will automatically be accommodated and displayed in an appropriately configured UIScrollView. However, there is one problem: The main reason I wanted to display things in a UIScrollView was so that, when the on-screen-keyboard appeared, I could shift the view up to focus on the control that is currently being edited. To do this, I need access to the UniversalScroller object that is holding the current calculator's view. On the beganEditing: event of each control, I intended to use the [UniversalScroller.view scrollRectToVisible: animated:] method to move focus to the correct control. However, I am having trouble accessing the UniversalScroller. I tried assigning a reference to it as a property of each calculator UIViewController, but did't seem to have much luck. I've read about using Delegates but have had trouble working out exactly how they work. I'm looking for one of three things: Some explanation of how I can access the methods of a UIScrollView from a UIViewController whose view is contained within it. or Confirmation of my suspicions that making users scroll on a data entry form is bad, and I should just abandon scrollviews altogether and move the view up and down to the relevant position when the keyboard appears, then back when it disappears. or Some pointers on how I could go about redesigning the calculators (which are basically simple data entry forms using labels, sliders and textfields) to be contained within UITableViewCells (presumably in a UITableView, which I understand is a scrollview deep down) - I read a post on SO saying that that's a more pleasing way to make a data entry form, but I couldn't find any examples of that online. Screenshots would be nice. Anything to make my app more usable and naturally 'iPhone-like', since shuffling labels and textboxes around makes me feel like I am building a winforms app! I've only recently started with this platform and language, and despite being largely an Apple skeptic I definitely see the beauty in the way that it works. Help me solve this problem and I might fall in love completely. Dan

    Read the article

  • iphone sdk - problem pasting into current text location

    - by norskben
    Hi guys I'm trying to paste text right into where the cursor currently is. I have been trying to do what it says at: - http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html The main deal is that I can't just go textbox1.text (etc) because the textfield is in the middle of a custom cell. I want to just have some text added to where the cursor is (when I press a custom key on a keyboard). -I just want to paste a decimal into the textbox... The error I get is: 2010-05-15 22:37:20.797 PageControl[37962:207] * -[MyDetailController paste:]: unrecognized selector sent to instance 0x1973d10 2010-05-15 22:37:20.797 PageControl[37962:207] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '** -[MyDetailController paste:]: unrecognized selector sent to instance 0x1973d10' Note: I have access to the textfield tag (if that helps?) I'm a little past the beginner stage in objective-c, but still not great. My code is currently below, and at https://gist.github.com/d634329e5ddf52945989 Thanks all. MyDetailController.h @interface MyDetailController : UITableViewController <UITextFieldDelegate,UINavigationControllerDelegate> { //...(lots in here) } @end @interface UIResponder(UIResponderInsertTextAdditions) - (void) insertText: (NSString*) text; @end MyDetailController.m @implementation MyDetailController //.... (lots in here) - (void)addDecimal:(NSNotification *)notification { // Apend the Decimal to the TextField. //savedAmount.text = [savedAmount.text stringByAppendingString:@"."]; NSLog(@"Decimal Pressed"); NSLog(@"tagClicked: %d",tagClicked); switch (tagClicked) { case 7: //savedAmount.text = [savedAmount.text stringByAppendingString:@"."]; break; case 8: //goalAmount.text = [goalAmount.text stringByAppendingString:@"."]; break; case 9: //incrementAmount.text = [incrementAmount.text stringByAppendingString:@"."]; break; case 10: //incrementAmount.text = [incrementAmount.text stringByAppendingString:@"."]; break; } [self insertText:@"."]; } -(void)textFieldDidBeginEditing:(UITextField *)textfield{ //UITextField *theCell = (UITextField *)sender; tagClicked = textfield.tag; NSLog(@"textfield changed. tagClicked: %d",tagClicked); } @end @implementation UIResponder(UIResponderInsertTextAdditions) - (void) insertText: (NSString*) text { // Get a refererence to the system pasteboard because that's // the only one @selector(paste:) will use. UIPasteboard* generalPasteboard = [UIPasteboard generalPasteboard]; // Save a copy of the system pasteboard's items // so we can restore them later. NSArray* items = [generalPasteboard.items copy]; // Set the contents of the system pasteboard // to the text we wish to insert. generalPasteboard.string = text; // Tell this responder to paste the contents of the // system pasteboard at the current cursor location. [self paste: self]; // Restore the system pasteboard to its original items. generalPasteboard.items = items; // Free the items array we copied earlier. [items release]; } @end

    Read the article

  • NSFetchedResultsController: using of NSManagedObjectContext during update brings to crash

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

    Read the article

  • 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

  • Iphone SDK - adding UITableView to UIView

    - by Shashi
    Hi, I am trying to learn how to use different views, for this sample test app, i have a login page, upon successful logon, the user is redirected to a table view and then upon selection of an item in the table view, the user is directed to a third page showing details of the item. the first page works just fine, but the problem occurs when i go to the second page, the table shown doesn't have title and i cannot add title or toolbar or anything other than the content of the tables themselves. and when i click on the item, needless to say nothing happens. no errors as well. i am fairly new to programming and have always worked on Java but never on C(although i have some basic knowledge of C) and Objective C is new to me. Here is the code. import @interface NavigationTestAppDelegate : NSObject { UIWindow *window; UIViewController *viewController; IBOutlet UITextField *username; IBOutlet UITextField *password; IBOutlet UILabel *loginError; //UINavigationController *navigationController; } @property (nonatomic, retain) IBOutlet UIViewController *viewController; @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UITextField *username; @property (nonatomic, retain) IBOutlet UITextField *password; @property (nonatomic, retain) IBOutlet UILabel *loginError; -(IBAction) login; -(IBAction) hideKeyboard: (id) sender; @end import "NavigationTestAppDelegate.h" import "RootViewController.h" @implementation NavigationTestAppDelegate @synthesize window; @synthesize viewController; @synthesize username; @synthesize password; @synthesize loginError; pragma mark - pragma mark Application lifecycle -(IBAction) hideKeyboard: (id) sender{ [sender resignFirstResponder]; } (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after app launch //RootViewController *rootViewController = [[RootViewController alloc] init]; //[window addSubview:[navigationController view]]; [window addSubview:[viewController view]]; [window makeKeyAndVisible]; return YES; } -(IBAction) login { RootViewController *rootViewController = [[RootViewController alloc] init]; //NSString *user = [[NSString alloc] username. if([username.text isEqualToString:@"test"]&&[password.text isEqualToString:@"test"]){ [window addSubview:[rootViewController view]]; //[window addSubview:[navigationController view]]; [window makeKeyAndVisible]; //rootViewController.awakeFromNib; } else { loginError.text = @"LOGIN ERROR"; [window addSubview:[viewController view]]; [window makeKeyAndVisible]; } } (void)applicationWillTerminate:(UIApplication *)application { // Save data if appropriate } pragma mark - pragma mark Memory management (void)dealloc { //[navigationController release]; [viewController release]; [window release]; [super dealloc]; } @end import @interface RootViewController : UITableViewController { IBOutlet NSMutableArray *views; } @property (nonatomic, retain) IBOutlet NSMutableArray * views; @end // // RootViewController.m // NavigationTest // // Created by guest on 4/23/10. // Copyright MyCompanyName 2010. All rights reserved. // import "RootViewController.h" import "OpportunityOne.h" @implementation RootViewController @synthesize views; //@synthesize navigationViewController; pragma mark - pragma mark View lifecycle (void)viewDidLoad { views = [ [NSMutableArray alloc] init]; OpportunityOne *opportunityOneController; for (int i=1; i<=20; i++) { opportunityOneController = [[OpportunityOne alloc] init]; opportunityOneController.title = [[NSString alloc] initWithFormat:@"Opportunity %i",i]; [views addObject:[NSDictionary dictionaryWithObjectsAndKeys: [[NSString alloc] initWithFormat:@"Opportunity %i",i], @ "title", opportunityOneController, @"controller", nil]]; self.title=@"GPS"; } /*UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init]; temporaryBarButtonItem.title = @"Back"; self.navigationItem.backBarButtonItem = temporaryBarButtonItem; [temporaryBarButtonItem release]; */ //self.title =@"Global Platform for Sales"; [super viewDidLoad]; //[temporaryBarButtonItem release]; //[opportunityOneController release]; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } pragma mark - pragma mark Table view data source // Customize the number of sections in the table view. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [views count]; } // Customize the appearance of table view cells. - (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. cell.textLabel.text = [[views objectAtIndex:indexPath.row] objectForKey:@"title"]; return cell; } pragma mark - pragma mark Table view delegate (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //UIViewController *targetViewController = [[views objectAtIndex:indexPath.row] objectForKey:@"controller"]; UIViewController *targetViewController = [[views objectAtIndex:indexPath.row] objectForKey:@"controller"]; [[self navigationController] pushViewController:targetViewController animated:YES]; } 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 { [views release]; [super dealloc]; } @end Wow, i was finding it real hard to post the code. i apologize for the bad formatting, but i just couldn't get past the formatting rules for this text editor. Thanks, Shashi

    Read the article

  • How to manage memory using classes in Objective-C?

    - by Flipper
    This is my first time creating an iPhone App and I am having difficulty with the memory management because I have never had to deal with it before. I have a UITableViewController and it all works fine until I try to scroll down in the simulator. It crashes saying that it cannot allocate that much memory. I have narrowed it down to where the crash is occurring: - (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Dequeue or create a cell UITableViewCellStyle style = UITableViewCellStyleDefault; UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:@"BaseCell"]; if (!cell) cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"BaseCell"] autorelease]; NSString* crayon; // Retrieve the crayon and its color if (aTableView == self.tableView) { crayon = [[[self.sectionArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] getName]; } else { crayon = [FILTEREDKEYS objectAtIndex:indexPath.row]; } cell.textLabel.text = crayon; if (![crayon hasPrefix:@"White"]) cell.textLabel.textColor = [self.crayonColors objectForKey:crayon]; else cell.textLabel.textColor = [UIColor blackColor]; return cell; } Here is the getName method: - (NSString*)getName { return name; } name is defined as: @property (nonatomic, retain) NSString *name; Now sectionArray is an NSMutableArray with instances of a class that I created Term in it. Term has a method getName that returns a NSString*. The problem seems to be the part of where crayon is being set and getName is being called. I have tried adding autorelease, release, and other stuff like that but that just causes the entire app to crash before even launching. Also if I do: cell.textLabel.text = @"test"; //crayon; /*if (![crayon hasPrefix:@"White"]) cell.textLabel.textColor = [self.crayonColors objectForKey:crayon]; else cell.textLabel.textColor = [UIColor blackColor];*/ Then I get no error whatsoever and it all scrolls just fine. Thanks in advance for the help! Edit: Here is the full Log of when I try to run the app and the error it gives when it crashes: [Session started at 2010-12-29 04:23:38 -0500.] [Session started at 2010-12-29 04:23:44 -0500.] GNU gdb 6.3.50-20050815 (Apple version gdb-967) (Tue Jul 14 02:11:58 UTC 2009) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-apple-darwin".sharedlibrary apply-load-rules all Attaching to process 1429. gdb-i386-apple-darwin(1430,0x778720) malloc: * mmap(size=1420296192) failed (error code=12) error: can't allocate region ** set a breakpoint in malloc_error_break to debug gdb stack crawl at point of internal error: [ 0 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (align_down+0x0) [0x1222d8] [ 1 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (xstrvprintf+0x0) [0x12336c] [ 2 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (xmalloc+0x28) [0x12358f] [ 3 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (dyld_info_read_raw_data+0x50) [0x1659af] [ 4 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (dyld_info_read+0x1bc) [0x168a58] [ 5 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (macosx_dyld_update+0xbf) [0x168c9c] [ 6 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (macosx_solib_add+0x36b) [0x169fcc] [ 7 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (macosx_child_attach+0x478) [0x17dd11] [ 8 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (attach_command+0x5d) [0x64ec5] [ 9 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (mi_cmd_target_attach+0x4c) [0x15dbd] [ 10 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (captured_mi_execute_command+0x16d) [0x17427] [ 11 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (catch_exception+0x41) [0x7a99a] [ 12 ] /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/libexec/gdb/gdb-i386-apple-darwin (mi_execute_command+0xa9) [0x16f63] /SourceCache/gdb/gdb-967/src/gdb/utils.c:1144: internal-error: virtual memory exhausted: can't allocate 1420296192 bytes. A problem internal to GDB has been detected, further debugging may prove unreliable. The Debugger has exited with status 1.The Debugger has exited with status 1. Here is the backtrace that I get when I set the breakpoint for malloc_error_break: #0 0x0097a68c in objc_msgSend () #1 0x01785bef in -[UILabel setText:] () #2 0x000030e0 in -[TableViewController tableView:cellForRowAtIndexPath:] (self=0x421d760, _cmd=0x29cfad8, aTableView=0x4819600, indexPath=0x42190f0) at /Volumes/Main2/Enayet/TableViewController.m:99 #3 0x016cee0c in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] () #4 0x016c6a43 in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] () #5 0x016d954f in -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow] () #6 0x016d08ff in -[UITableView layoutSubviews] () #7 0x03e672b0 in -[CALayer layoutSublayers] () #8 0x03e6706f in CALayerLayoutIfNeeded () #9 0x03e668c6 in CA::Context::commit_transaction () #10 0x03e6653a in CA::Transaction::commit () #11 0x03e6e838 in CA::Transaction::observer_callback () #12 0x00b00252 in __CFRunLoopDoObservers () #13 0x00aff65f in CFRunLoopRunSpecific () #14 0x00afec48 in CFRunLoopRunInMode () #15 0x00156615 in GSEventRunModal () #16 0x001566da in GSEventRun () #17 0x01689faf in UIApplicationMain () #18 0x00002398 in main (argc=1, argv=0xbfffefb0) at /Volumes/Main2/Enayet/main.m:14

    Read the article

  • EXC_BAD_ACCESS at UITableView on IOS

    - by Suprie
    Hi all, When scrolling through table, my application crash and console said it was EXC_BAD_ACCESS. I've look everywhere, and people suggest me to use NSZombieEnabled on my executables environment variables. I've set NSZombieEnabled, NSDebugEnabled, MallocStackLogging and MallocStackLoggingNoCompact to YES on my executables. But apparently i still can't figure out which part of my program that cause EXC_BAD_ACCESS. This is what my console said [Session started at 2010-12-21 21:11:21 +0700.] GNU gdb 6.3.50-20050815 (Apple version gdb-1510) (Wed Sep 22 02:45:02 UTC 2010) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "x86_64-apple-darwin".sharedlibrary apply-load-rules all Attaching to process 9335. TwitterSearch(9335) malloc: recording malloc stacks to disk using standard recorder TwitterSearch(9335) malloc: process 9300 no longer exists, stack logs deleted from /tmp/stack-logs.9300.TwitterSearch.suirlR.index TwitterSearch(9335) malloc: stack logs being written into /tmp/stack- logs.9335.TwitterSearch.tQJAXk.index 2010-12-21 21:11:25.446 TwitterSearch[9335:207] View Did Load Program received signal: “EXC_BAD_ACCESS”. And this is when i tried to type backtrace on gdb : Program received signal: “EXC_BAD_ACCESS”. (gdb) backtrace #0 0x00f20a67 in objc_msgSend () #1 0x0565cd80 in ?? () #2 0x0033b7fa in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] () #3 0x0033177f in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] () #4 0x00346450 in -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] () #5 0x0033e538 in -[UITableView layoutSubviews] () #6 0x01ffc451 in -[CALayer layoutSublayers] () #7 0x01ffc17c in CALayerLayoutIfNeeded () #8 0x01ff537c in CA::Context::commit_transaction () #9 0x01ff50d0 in CA::Transaction::commit () #10 0x020257d5 in CA::Transaction::observer_callback () #11 0x00d9ffbb in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ () #12 0x00d350e7 in __CFRunLoopDoObservers () #13 0x00cfdbd7 in __CFRunLoopRun () #14 0x00cfd240 in CFRunLoopRunSpecific () #15 0x00cfd161 in CFRunLoopRunInMode () #16 0x01a73268 in GSEventRunModal () #17 0x01a7332d in GSEventRun () #18 0x002d642e in UIApplicationMain () #19 0x00001d4e in main (argc=1, argv=0xbfffee34) at /Users/suprie/Documents/Projects/Self/cocoa/TwitterSearch/main.m:14 I really appreciate for any clue to help me debug my application. EDIT this is the Header file of table #import <UIKit/UIKit.h> @interface TwitterTableViewController : UITableViewController { NSMutableArray *twitters; } @property(nonatomic,retain) NSMutableArray *twitters; @end and the implementation file #import "TwitterTableViewController.h" @implementation TwitterTableViewController @synthesize twitters; #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [twitters count]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 90.0f; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { const NSInteger TAG_IMAGE_VIEW = 1001; const NSInteger TAG_TWEET_VIEW = 1002; const NSInteger TAG_FROM_VIEW = 1003; static NSString *CellIdentifier = @"Cell"; UIImageView *imageView; UILabel *tweet; UILabel *from; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; // Image imageView = [[[[UIImageView alloc] initWithFrame:CGRectMake(5.0f, 5.0f, 60.0f, 60.0f)] autorelease] retain]; [cell.contentView addSubview:imageView]; imageView.tag = TAG_IMAGE_VIEW; // Tweet tweet = [[[UILabel alloc] initWithFrame:CGRectMake(105.0f, 5.0f, 200.0f, 50.0f)] autorelease]; [cell.contentView addSubview:tweet]; tweet.tag = TAG_TWEET_VIEW; tweet.numberOfLines = 2; tweet.font = [UIFont fontWithName:@"Helvetica" size:12]; tweet.textColor = [UIColor blackColor]; tweet.backgroundColor = [UIColor clearColor]; // From from = [[[UILabel alloc] initWithFrame:CGRectMake(105.0f, 55.0, 200.0f, 35.0f)] autorelease]; [cell.contentView addSubview:from]; from.tag = TAG_FROM_VIEW; from.numberOfLines = 1; from.font = [UIFont fontWithName:@"Helvetica" size:10]; from.textColor = [UIColor blackColor]; from.backgroundColor = [UIColor clearColor]; } // Configure the cell... NSMutableDictionary *twitter = [twitters objectAtIndex:(NSInteger) indexPath.row]; // cell.text = [twitter objectForKey:@"text"]; tweet.text = (NSString *) [twitter objectForKey:@"text"]; tweet.hidden = NO; from.text = (NSString *) [twitter objectForKey:@"from_user"]; from.hidden = NO; NSString *avatar_url = (NSString *)[twitter objectForKey:@"profile_image_url"]; NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: avatar_url]]; imageView.image = [UIImage imageWithData: imageData]; imageView.hidden = NO; return cell; } #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSMutableDictionary *twitter = [twitters objectAtIndex:(NSInteger)indexPath.row]; NSLog(@"Twit ini kepilih :%@", [twitter objectForKey:@"text"]); } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; } - (void)viewDidUnload { } - (void)dealloc { [super dealloc]; } @end

    Read the article

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

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

    Read the article

  • UITableView not displaying parsed data

    - by Graeme
    I have a UITableView which is setup in Interface Builder and connected properly to its class in Xcode. I also have a "Importer" Class which downloads and parses an RSS feed and stores the information in an NSMutableArray. However I have verified the parsing is working properly (using breakpoints and NSlog) but no data is showing in the UITable View. Any ideas as to what the problem could be? I'm almost out of them. It's based on the XML performance Apple example. Here's the code for TableView.h: #import <UIKit/UIKit.h> #import "IncidentsImporter.h" @class SongDetailsController; @interface CurrentIncidentsTableViewController : UITableViewController <IncidentsImporterDelegate>{ NSMutableArray *incidents; SongDetailsController *detailController; UITableView *ctableView; IncidentsImporter *parser; } @property (nonatomic, retain) NSMutableArray *incidents; @property (nonatomic, retain, readonly) SongDetailsController *detailController; @property (nonatomic, retain) IncidentsImporter *parser; @property (nonatomic, retain) IBOutlet UITableView *ctableView; // Called by the ParserChoiceViewController based on the selected parser type. - (void)beginParsing; @end And the code for .m: #import "CurrentIncidentsTableViewController.h" #import "SongDetailsController.h" #import "Incident.h" @implementation CurrentIncidentsTableViewController @synthesize ctableView, incidents, parser, detailController; #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { [super viewDidLoad]; self.parser = [[IncidentsImporter alloc] init]; parser.delegate = self; [parser start]; UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(beginParsing)]; self.navigationItem.rightBarButtonItem = refreshButton; [refreshButton release]; // Uncomment the following line to preserve selection between presentations. //self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } - (void)viewWillAppear:(BOOL)animated { NSIndexPath *selectedRowIndexPath = [ctableView indexPathForSelectedRow]; if (selectedRowIndexPath != nil) { [ctableView deselectRowAtIndexPath:selectedRowIndexPath animated:NO]; } } // This method will be called repeatedly - once each time the user choses to parse. - (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.incidents = [NSMutableArray array]; } else { [incidents removeAllObjects]; [ctableView reloadData]; } // Create the parser, set its delegate, and start it. self.parser = [[IncidentsImporter alloc] init]; parser.delegate = self; [parser start]; } /* - (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 { // Override to allow orientations other than the default portrait orientation. return YES; } #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [incidents count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Table Cell Sought"); static NSString *kCellIdentifier = @"MyCell"; UITableViewCell *cell = [ctableView dequeueReusableCellWithIdentifier:kCellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease]; cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } cell.textLabel.text = @"Test";//[[incidents objectAtIndex:indexPath.row] title]; return cell; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.detailController.incident = [incidents objectAtIndex:indexPath.row]; [self.navigationController pushViewController:self.detailController animated:YES]; } #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)parserDidEndParsingData:(IncidentsImporter *)parser { [ctableView reloadData]; self.navigationItem.rightBarButtonItem.enabled = YES; self.parser = nil; } - (void)parser:(IncidentsImporter *)parser didParseIncidents:(NSArray *)parsedIncidents { //[incidents addObjectsFromArray: parsedIncidents]; // Three scroll view properties are checked to keep the user interface smooth during parse. When new objects are delivered by the parser, the table view is reloaded to display them. If the table is reloaded while the user is scrolling, this can result in eratic behavior. dragging, tracking, and decelerating can be checked for this purpose. When the parser finishes, reloadData will be called in parserDidEndParsingData:, guaranteeing that all data will ultimately be displayed even if reloadData is not called in this method because of user interaction. if (!ctableView.dragging && !ctableView.tracking && !ctableView.decelerating) { self.title = [NSString stringWithFormat:NSLocalizedString(@"Top %d Songs", @"Top Songs format"), [parsedIncidents count]]; [ctableView reloadData]; } } - (void)parser:(IncidentsImporter *)parser didFailWithError:(NSError *)error { // handle errors as appropriate to your application... } - (void)dealloc { [super dealloc]; } @end

    Read the article

  • Yet another UITableView Question

    - by barbgal
    Hi, I have a strange issue in my iPhone application. I have created a UITableView with 4 Sections and 3 Rows so totally 12 Rows. But - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath The above method only gets called for 9 times instead of 12 times.why this happenning. My 4th section is not getting constructed but my 1st section gets duplicated as 4th section. Thanks for your time and help. Plese refer my code below @interface MainViewController : UITableViewController<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource> { } @end // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { CGRect frameRect = CGRectMake(0,0,320,460); UITableView *tableView = [[UITableView alloc] initWithFrame:frameRect style:UITableViewStyleGrouped]; tableView.delegate = self; tableView.dataSource = self; tableView.backgroundColor = [UIColor purpleColor]; tableView.scrollEnabled = YES; self.view = tableView; [tableView release]; [super viewDidLoad]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return 3; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 4; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"CELL IS NIL %i", indexPath.section); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; if (indexPath.section == 0) { if(indexPath.row == 0) { cell.text = @"Tmail"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else if ( indexPath.row == 1 ) { cell.text = @"English"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else { cell.text = @"Hindi"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } } else if (indexPath.section == 1) { if(indexPath.row == 0) { cell.text = @"Street"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else if ( indexPath.row == 1 ) { cell.text = @"City"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else { cell.text = @"State"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } } else if (indexPath.section == 2) { if(indexPath.row == 0) { cell.text = @"Salem"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else if ( indexPath.row == 1 ) { cell.text = @"Samalpatti"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else { cell.text = @"Chennai"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } } else if (indexPath.section == 3) { if(indexPath.row == 0) { cell.text = @"NOKIA"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else if ( indexPath.row == 1) { cell.text = @"SAMSUNG"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else { cell.text = @"SONY"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } } } return cell; }

    Read the article

  • Popping UIView crashes app

    - by Adun
    I'm basically pushing a UIView from a UITableViewController and all it contains is a UIWebView. However when I remove the UIView to return back to the UITableView the app crashes. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. if (indexPath.row == websiteCell) { NSString *urlPath = [NSString stringWithFormat:@"http://%@", exhibitor.website]; WebViewController *webViewController = [[WebViewController alloc] initWithURLString:urlPath]; // Pass the selected object to the new view controller. [self.parentViewController presentModalViewController:webViewController animated:YES]; [webViewController release]; } } If I comment out the [webViewController release] the app doesn't crash, but I know that this would be a leak. Below is the code for the Web Browser: #import "WebViewController.h" @implementation WebViewController @synthesize webBrowserView; @synthesize urlValue; @synthesize toolBar; @synthesize spinner; @synthesize loadUrl; -(id)initWithURLString:(NSString *)urlString { if (self = [super init]) { urlValue = urlString; } return self; } #pragma mark WebView Controls - (void)goBack { [webBrowserView goBack]; } - (void)goForward { [webBrowserView goForward]; } - (void)reload { [webBrowserView reload]; } - (void)closeBrowser { [self.parentViewController dismissModalViewControllerAnimated:YES]; } #pragma end // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; CGRect contentRect = self.view.bounds; //NSLog(@"%f", contentRect.size.height); float webViewHeight = contentRect.size.height - 44.0f; // navBar = 44 float toolBarHeight = contentRect.size.height - webViewHeight; // navigation bar UINavigationBar *navBar = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, contentRect.size.width, 44)] autorelease]; navBar.delegate = self; UIBarButtonItem *doneButton = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:nil action:@selector(closeBrowser)] autorelease]; UINavigationItem *item = [[[UINavigationItem alloc] initWithTitle:@"CEDIA10"] autorelease]; item.leftBarButtonItem = doneButton; [navBar pushNavigationItem:item animated:NO]; [self.view addSubview:navBar]; // web browser webBrowserView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, contentRect.size.width, webViewHeight)]; webBrowserView.delegate = self; webBrowserView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; webBrowserView.scalesPageToFit = YES; [self.view addSubview:webBrowserView]; // buttons UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowleft.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)] autorelease]; UIBarButtonItem *fwdButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowright.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goForward)] autorelease]; UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload)] autorelease]; UIBarButtonItem *flexSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease]; UIBarButtonItem *fixSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil] autorelease]; [fixSpace setWidth: 40.0f]; spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease]; [spinner startAnimating]; UIBarButtonItem *loadingIcon = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease]; NSArray *toolBarButtons = [[NSArray alloc] initWithObjects: fixSpace, backButton, fixSpace, fwdButton, flexSpace, loadingIcon, flexSpace, refreshButton, nil]; // toolbar toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, webViewHeight, contentRect.size.width, toolBarHeight)]; toolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth; toolBar.items = toolBarButtons; [self.view addSubview:toolBar]; // load the request NSURL *requestString = [NSURL URLWithString:urlValue]; [webBrowserView loadRequest:[NSURLRequest requestWithURL: requestString]]; [toolBarButtons release]; } - (void)viewWillDisappear { if ([webBrowserView isLoading]) { [webBrowserView stopLoading]; webBrowserView.delegate = nil; } } #pragma mark UIWebView - (void)webViewDidStartLoad:(UIWebView*)webView { [spinner startAnimating]; } - (void)webViewDidFinishLoad:(UIWebView*)webView { [spinner stopAnimating]; } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { loadUrl = [[request URL] retain]; if ([[loadUrl scheme] isEqualToString: @"mailto"]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CEDIA10" message:@"Do you want to open Mail and exit AREC10?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes",nil]; [alert show]; [alert release]; return NO; } [loadUrl release]; return YES; } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { [spinner stopAnimating]; if (error.code == -1009) { // no internet connection UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CEDIA10" message:@"You need an active Internet connection." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } } #pragma mark UIAlertView - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { [[UIApplication sharedApplication] openURL:loadUrl]; [loadUrl release]; } } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. [webBrowserView release]; [urlValue release]; [toolBar release]; [spinner release]; [loadUrl release]; webBrowserView = nil; webBrowserView.delegate = nil; urlValue = nil; toolBar = nil; spinner = nil; loadUrl = nil; } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [webBrowserView release]; [urlValue release]; [toolBar release]; [spinner release]; [loadUrl release]; webBrowserView.delegate = nil; urlValue = nil; toolBar = nil; spinner = nil; loadUrl = nil; [super dealloc]; } @end Below this is the crash log that I am getting: Date/Time: 2010-05-13 11:58:20.023 +1000 OS Version: iPhone OS 3.1.3 (7E18) Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x00000000, 0x00000000 Crashed Thread: 0 Thread 0 Crashed: 0 libSystem.B.dylib 0x00090b2c __kill + 8 1 libSystem.B.dylib 0x00090b1a kill + 4 2 libSystem.B.dylib 0x00090b0e raise + 10 3 libSystem.B.dylib 0x000a7e34 abort + 36 4 libstdc++.6.dylib 0x00066390 __gnu_cxx::__verbose_terminate_handler() + 588 5 libobjc.A.dylib 0x00008898 _objc_terminate + 160 6 libstdc++.6.dylib 0x00063a84 __cxxabiv1::__terminate(void (*)()) + 76 7 libstdc++.6.dylib 0x00063afc std::terminate() + 16 8 libstdc++.6.dylib 0x00063c24 __cxa_throw + 100 9 libobjc.A.dylib 0x00006e54 objc_exception_throw + 104 10 CoreFoundation 0x00095bf6 -[NSObject doesNotRecognizeSelector:] + 106 11 CoreFoundation 0x0001ab12 ___forwarding___ + 474 12 CoreFoundation 0x00011838 _CF_forwarding_prep_0 + 40 13 QuartzCore 0x0000f448 CALayerCopyRenderLayer + 24 14 QuartzCore 0x0000f048 CA::Context::commit_layer(_CALayer*, unsigned int, unsigned int, void*) + 100 15 QuartzCore 0x0000ef34 CALayerCommitIfNeeded + 336 16 QuartzCore 0x0000eedc CALayerCommitIfNeeded + 248 17 QuartzCore 0x00011ee8 CA::Context::commit_root(void*, void*) + 52 18 QuartzCore 0x00011e80 x_hash_table_foreach + 64 19 QuartzCore 0x00011e2c CA::Transaction::foreach_root(void (*)(void*, void*), void*) + 40 20 QuartzCore 0x0000bb68 CA::Context::commit_transaction(CA::Transaction*) + 1068 21 QuartzCore 0x0000b46c CA::Transaction::commit() + 276 22 QuartzCore 0x000135d4 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 84 23 CoreFoundation 0x0000f82a __CFRunLoopDoObservers + 466 24 CoreFoundation 0x00057340 CFRunLoopRunSpecific + 1812 25 CoreFoundation 0x00056c18 CFRunLoopRunInMode + 44 26 GraphicsServices 0x000041c0 GSEventRunModal + 188 27 UIKit 0x00003c28 -[UIApplication _run] + 552 28 UIKit 0x00002228 UIApplicationMain + 960 29 CEDIA10 0x00002e16 main (main.m:14) 30 CEDIA10 0x00002db8 start + 32 Any ideas on why the app is crashing?

    Read the article

  • NOOB Memory Problem - EXC_BAD_ACCESS (OBJ-C/iPhone)

    - by Michael Bordelon
    I have been banging my head against the wall for a couple days and need some help. I have a feeling that I am doing something really silly here, but I cannot find the issue. This is the controller for a table view. I put the SQL in line to simplify it as part of the troubleshooting of this error. Normally, it would be in an accessor method in a model class. It gets through the SQL read just fine. Finds the two objects, loads them into the todaysWorkout array and then builds the cells for the table view. The table view actually comes up on the scree and then it throws the EXC_BAD_ACCESS. I ran instruments and it shows the following: 0 CFString Malloc 1 00:03.765 0x3946470 176 Foundation -[NSPlaceholderString initWithFormat:locale:arguments:] 1 CFString Autorelease 00:03.765 0x3946470 0 Foundation NSRecordAllocationEvent 2 CFString CFRelease 0 00:03.767 0x3946470 0 Bring It -[WorkoutViewController viewDidLoad] 3 CFString Zombie -1 00:03.917 0x3946470 0 Foundation NSPopAutoreleasePool Here is the source code for the controller. I left it all in there just in case there is something extraneous causing the problem. I sincerely appreciate any help I can get: HEADER: #import <UIKit/UIKit.h> #import <sqlite3.h> #import "NoteCell.h" #import "BIUtility.h" #import "Bring_ItAppDelegate.h" #import "MoveListViewController.h" @class MoveListViewController; @class BIUtility; @interface WorkoutViewController : UITableViewController { NSMutableArray *todaysWorkouts; IBOutlet NoteCell *woNoteCell; MoveListViewController *childController; NSInteger scheduleDay; BIUtility *bi; } @property (nonatomic, retain) NSMutableArray *todaysWorkouts; @property (nonatomic, retain) NoteCell *woNoteCell; @property (nonatomic,retain) BIUtility *bi; //@property (nonatomic, retain) SwitchCell *woSwitchCell; @end CLASS: #import "WorkoutViewController.h" #import "MoveListViewController.h" #import "Profile.h" static sqlite3 *database = nil; @implementation WorkoutViewController @synthesize todaysWorkouts; @synthesize woNoteCell; @synthesize bi; //@synthesize woSwitchCell; - (void)viewDidLoad { [super viewDidLoad]; bi = [[BIUtility alloc] init]; todaysWorkouts = [[NSMutableArray alloc] init]; NSString *query; sqlite3_stmt *statement; //open the database if (sqlite3_open([[BIUtility getDBPath] UTF8String], &database) != SQLITE_OK) { sqlite3_close(database); NSAssert(0, @"Failed to opendatabase"); } query = [NSString stringWithFormat:@"SELECT IWORKOUT.WOINSTANCEID, IWORKOUT.WORKOUTID, CWORKOUTS.WORKOUTNAME FROM CWORKOUTS JOIN IWORKOUT ON IWORKOUT.WORKOUTID = CWORKOUTS.WORKOUTID AND DATE = '%@'", [BIUtility todayDateString]]; if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { Workout *wo = [[Workout alloc] init]; wo.woInstanceID = sqlite3_column_int(statement, 0); wo.workoutID = sqlite3_column_int(statement, 1); wo.workoutName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)]; [todaysWorkouts addObject:wo]; [wo release]; } sqlite3_finalize(statement); } if(database) sqlite3_close(database); [query release]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //todaysWorkouts = [BIUtility todaysScheduledWorkouts]; static NSString *noteCellIdentifier = @"NoteCellIdentifier"; UITableViewCell *cell; if (indexPath.section < ([todaysWorkouts count])) { cell = [tableView dequeueReusableCellWithIdentifier:@"OtherCell"]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: @"OtherCell"] autorelease]; cell.accessoryType = UITableViewCellAccessoryNone; } if (indexPath.row == 0) { Workout *wo = [todaysWorkouts objectAtIndex:indexPath.section]; [cell.textLabel setText:wo.workoutName]; } else { [cell.textLabel setText:@"Completed?"]; [cell.textLabel setFont:[UIFont fontWithName:@"Arial" size:15]]; [cell.textLabel setTextColor:[UIColor blueColor]]; } } else { cell = (NoteCell *)[tableView dequeueReusableCellWithIdentifier:noteCellIdentifier]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"NoteCell" owner:self options:nil]; cell = [nib objectAtIndex:0]; } } return cell; //[cell release]; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger row = [indexPath row]; if (indexPath.section < ([todaysWorkouts count]) && (row == 0)) { MoveListViewController *moveListController = [[MoveListViewController alloc] initWithStyle:UITableViewStylePlain]; moveListController.workoutID = [[todaysWorkouts objectAtIndex:indexPath.section] workoutID]; moveListController.workoutName = [[todaysWorkouts objectAtIndex:indexPath.section] workoutName]; moveListController.woInstanceID = [[todaysWorkouts objectAtIndex:indexPath.section] woInstanceID]; NSLog(@"Workout Selected: %@", [[todaysWorkouts objectAtIndex:indexPath.section] workoutName]); Bring_ItAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; [delegate.workoutNavController pushViewController:moveListController animated:YES]; } else { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if (indexPath.section < ([todaysWorkouts count]) && (row == 1)) { if (cell.accessoryType == UITableViewCellAccessoryNone) { cell.accessoryType = UITableViewCellAccessoryCheckmark; } else { cell.accessoryType = UITableViewCellAccessoryNone; } } } [tableView deselectRowAtIndexPath:indexPath animated:YES]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSInteger h = 35; return h; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return ([todaysWorkouts count] + 1); //return ([todaysWorkouts count]); } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (section < ([todaysWorkouts count])) { return 2; } else { return 1; } } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { if (section < ([todaysWorkouts count])) { return @"Workout"; } else { return @"How Was Your Workout?"; } } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [todaysWorkouts release]; [bi release]; [super dealloc]; } @end

    Read the article

  • Adding Custom Object to NSMutableArray

    - by Fozz
    Developing ios app. I have an object class Product.h and .m respectively along with my picker class which implements my vehicle selection to match products to vehicle. The files product.h #import <Foundation/Foundation.h> @interface Product : NSObject { } @property (nonatomic, retain) NSString *iProductID; @property (nonatomic, retain) NSString *vchProductCode; @property (nonatomic, retain) NSString *vchPriceCode; @property (nonatomic, retain) NSString *vchHitchUPC; @property (nonatomic, retain) NSString *mHitchList; @property (nonatomic, retain) NSString *mHitchMap; @property (nonatomic, retain) NSString *fShippingWeight; @property (nonatomic, retain) NSString *vchWC; @property (nonatomic, retain) NSString *vchCapacity; @property (nonatomic, retain) NSString *txtNote1; @property (nonatomic, retain) NSString *txtNote2; @property (nonatomic, retain) NSString *txtNote3; @property (nonatomic, retain) NSString *txtNote4; @property (nonatomic, retain) NSString *vchDrilling; @property (nonatomic, retain) NSString *vchUPCList; @property (nonatomic, retain) NSString *vchExposed; @property (nonatomic, retain) NSString *vchShortDesc; @property (nonatomic, retain) NSString *iVehicleID; @property (nonatomic, retain) NSString *iProductClassID; @property (nonatomic, retain) NSString *dtDateMod; @property (nonatomic, retain) NSString *txtBullet1; @property (nonatomic, retain) NSString *txtBullet2; @property (nonatomic, retain) NSString *txtBullet3; @property (nonatomic, retain) NSString *txtBullet4; @property (nonatomic, retain) NSString *txtBullet5; @property (nonatomic, retain) NSString *iUniqueIdentifier; @property (nonatomic, retain) NSString *dtDateLastTouched; @property (nonatomic, retain) NSString *txtNote6; @property (nonatomic, retain) NSString *InstallTime; @property (nonatomic, retain) NSString *SGID; @property (nonatomic, retain) NSString *CURTID; @property (nonatomic, retain) NSString *SGRetail; @property (nonatomic, retain) NSString *SGMemPrice; @property (nonatomic, retain) NSString *InstallSheet; @property (nonatomic, retain) NSString *mHitchJobber; @property (nonatomic, retain) NSString *CatID; @property (nonatomic, retain) NSString *ParentID; -(id) initWithDict:(NSDictionary *)dic; -(NSString *) description; @end Product implementation .m #import "Product.h" @implementation Product @synthesize iProductID; @synthesize vchProductCode; @synthesize vchPriceCode; @synthesize vchHitchUPC; @synthesize mHitchList; @synthesize mHitchMap; @synthesize fShippingWeight; @synthesize vchWC; @synthesize vchCapacity; @synthesize txtNote1; @synthesize txtNote2; @synthesize txtNote3; @synthesize txtNote4; @synthesize vchDrilling; @synthesize vchUPCList; @synthesize vchExposed; @synthesize vchShortDesc; @synthesize iVehicleID; @synthesize iProductClassID; @synthesize dtDateMod; @synthesize txtBullet1; @synthesize txtBullet2; @synthesize txtBullet3; @synthesize txtBullet4; @synthesize txtBullet5; @synthesize iUniqueIdentifier; @synthesize dtDateLastTouched; @synthesize txtNote6; @synthesize InstallTime; @synthesize SGID; @synthesize CURTID; @synthesize SGRetail; @synthesize SGMemPrice; @synthesize InstallSheet; @synthesize mHitchJobber; @synthesize CatID; @synthesize ParentID; -(id) initWithDict:(NSDictionary *)dic { [super init]; //Initialize all variables self.iProductID = [[NSString alloc] initWithString:[dic objectForKey:@"iProductID"]]; self.vchProductCode = [[NSString alloc] initWithString:[dic objectForKey:@"vchProductCode"]]; self.vchPriceCode = [[NSString alloc] initWithString:[dic objectForKey:@"vchPriceCode"]]; self.vchHitchUPC = [[NSString alloc] initWithString:[dic objectForKey:@"vchHitchUPC"]]; self.mHitchList = [[NSString alloc] initWithString:[dic objectForKey:@"mHitchList"]]; self.mHitchMap = [[NSString alloc] initWithString:[dic objectForKey:@"mHitchMap"]]; self.fShippingWeight = [[NSString alloc] initWithString:[dic objectForKey:@"fShippingWeight"]]; self.vchWC = [[NSString alloc] initWithString:[dic objectForKey:@"vchWC"]]; self.vchCapacity = [[NSString alloc] initWithString:[dic objectForKey:@"vchCapacity"]]; self.txtNote1 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote1"]]; self.txtNote2 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote2"]]; self.txtNote3 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote3"]]; self.txtNote4 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote4"]]; self.vchDrilling = [[NSString alloc] initWithString:[dic objectForKey:@"vchDrilling"]]; self.vchUPCList = [[NSString alloc] initWithString:[dic objectForKey:@"vchUPCList"]]; self.vchExposed = [[NSString alloc] initWithString:[dic objectForKey:@"vchExposed"]]; self.vchShortDesc = [[NSString alloc] initWithString:[dic objectForKey:@"vchShortDesc"]]; self.iVehicleID = [[NSString alloc] initWithString:[dic objectForKey:@"iVehicleID"]]; self.iProductClassID = [[NSString alloc] initWithString:[dic objectForKey:@"iProductClassID"]]; self.dtDateMod = [[NSString alloc] initWithString:[dic objectForKey:@"dtDateMod"]]; self.txtBullet1 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet1"]]; self.txtBullet2 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet2"]]; self.txtBullet3 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet3"]]; self.txtBullet4 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet4"]]; self.txtBullet5 = [[NSString alloc] initWithString:[dic objectForKey:@"txtBullet5"]]; self.iUniqueIdentifier = [[NSString alloc] initWithString:[dic objectForKey:@"iUniqueIdentifier"]]; self.dtDateLastTouched = [[NSString alloc] initWithString:[dic objectForKey:@"dtDateLastTouched"]]; self.txtNote6 = [[NSString alloc] initWithString:[dic objectForKey:@"txtNote6"]]; self.InstallTime = [[NSString alloc] initWithString:[dic objectForKey:@"InstallTime"]]; self.SGID = [[NSString alloc] initWithString:[dic objectForKey:@"SGID"]]; self.CURTID = [[NSString alloc] initWithString:[dic objectForKey:@"CURTID"]]; self.SGRetail = [[NSString alloc] initWithString:[dic objectForKey:@"SGRetail"]]; self.SGMemPrice = [[NSString alloc] initWithString:[dic objectForKey:@"SGMemPrice"]]; self.InstallSheet = [[NSString alloc] initWithString:[dic objectForKey:@"InstallSheet"]]; self.mHitchJobber = [[NSString alloc] initWithString:[dic objectForKey:@"mHitchJobber"]]; self.CatID = [[NSString alloc] initWithString:[dic objectForKey:@"CatID"]]; self.ParentID = [[NSString alloc] initWithString:[dic objectForKey:@"ParentID"]]; return self; } -(NSString *) description { return [NSString stringWithFormat:@"iProductID = %@\n vchProductCode = %@\n vchPriceCode = %@\n vchHitchUPC = %@\n mHitchList = %@\n mHitchMap = %@\n fShippingWeight = %@\n vchWC = %@\n vchCapacity = %@\n txtNote1 = %@\n txtNote2 = %@\n txtNote3 = %@\n txtNote4 = %@\n vchDrilling = %@\n vchUPCList = %@\n vchExposed = %@\n vchShortDesc = %@\n iVehicleID = %@\n iProductClassID = %@\n dtDateMod = %@\n txtBullet1 = %@\n txtBullet2 = %@\n txtBullet3 = %@\n txtBullet4 = %@\n txtBullet4 = %@\n txtBullet5 = %@\n iUniqueIdentifier = %@\n dtDateLastTouched = %@\n txtNote6 = %@\n InstallTime = %@\n SGID = %@\n CURTID = %@\n SGRetail = %@\n SGMemPrice = %@\n InstallSheet = %@\n mHitchJobber = %@\n CatID = %@\n ParentID = %@\n", iProductID, vchProductCode, vchPriceCode, vchHitchUPC, mHitchList, mHitchMap, fShippingWeight, vchWC, vchCapacity, txtNote1, txtNote2, txtNote3, txtNote4, vchDrilling, vchUPCList, vchExposed, vchShortDesc, iVehicleID, iProductClassID, dtDateMod, txtBullet1, txtBullet2, txtBullet3, txtBullet4,txtBullet5, iUniqueIdentifier, dtDateLastTouched,txtNote6,InstallTime,SGID,CURTID,SGRetail,SGMemPrice,InstallSheet,mHitchJobber,CatID, ParentID]; } @end Ignoring the fact that its really long I also tried to just set the property but then my product didnt have any values. So I alloc'd for all properties, not sure which is "correct" the use of product picker.h #import <UIKit/UIKit.h> @class Vehicle; @class Product; @interface Picker : UITableViewController <NSXMLParserDelegate> { NSString *currentRow; NSString *currentElement; Vehicle *vehicle; } @property (nonatomic, retain) NSMutableArray *dataArray; //@property (readwrite, copy) NSString *currentRow; //@property (readwrite, copy) NSString *currentElement; -(void) getYears:(NSString *)string; -(void) getMakes:(NSString *)year; -(void) getModels:(NSString *)year: (NSString *)make; -(void) getStyles:(NSString *)year: (NSString *)make: (NSString *)model; -(void) getHitch:(NSString *)year: (NSString *)make: (NSString *)model: (NSString *)style; -(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName; -(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string; -(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict; @end The implementation .m #import "Product.h" #import "Picker.h" #import "KioskAppDelegate.h" #import "JSON.h" #import "Vehicle.h" @implementation Picker @synthesize dataArray; -(void) getHitch:(NSString *)year: (NSString *)make: (NSString *)model: (NSString *)style{ currentRow = [NSString stringWithString:@"z:row"]; currentElement = [NSString stringWithString:@"gethitch"]; //Reinitialize data array [self.dataArray removeAllObjects]; [self.dataArray release]; self.dataArray = [[NSArray alloc] initWithObjects:nil]; //Build url & string NSString *thisString = [[NSString alloc] initWithString:@""]; thisString = [NSString stringWithFormat:@"http://api.curthitch.biz/AJAX_CURT.aspx?action=GetHitch&dataType=json&year=%@&make=%@&model=%@&style=%@",year,make,model,style]; //Request NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:thisString]]; //Perform request and fill data with json NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Get string from data NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; //set up parser SBJsonParser *parser = [[SBJsonParser alloc] init]; //parse json into object NSArray *tempArray = [parser objectWithString:json_string error:nil]; for (NSDictionary *dic in tempArray) { Product *tempProduct = [[Product alloc] initWithDict:dic]; NSLog(@"is tempProduct valid %@", (tempProduct) ? @"YES" : @"NO"); [self.dataArray addObject:tempProduct]; } } @end So I stripped out all the table methods and misc crap that doesnt matter. In the end my problem is adding the "tempProduct" object to the mutable array dataArray so that I can customize the table cells. Using the json framework im parsing out some json which returns an array of NSDictionary objects. Stepping through that my dictionary objects look good, I populate my custom object with properties for all my fields which goes through fine, and the values look right. However I cant add this to the array, I've tried several different implementations doesn't work. Not sure what I'm doing wrong. In some instances doing a po tempProduct prints the description and sometimes it does not. same with right clicking on the variable and choosing print description. Actual error message 2011-02-22 15:53:56.058 Kiosk[8547:207] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x4e1ba40 2011-02-22 15:53:56.060 Kiosk[8547:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x4e1ba40' *** Call stack at first throw: ( 0 CoreFoundation 0x00dbabe9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x00f0f5c2 objc_exception_throw + 47 2 CoreFoundation 0x00dbc6fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x00d2c366 ___forwarding___ + 966 4 CoreFoundation 0x00d2bf22 _CF_forwarding_prep_0 + 50 5 Kiosk 0x00003ead -[Picker getHitch::::] + 1091 6 Kiosk 0x00003007 -[Picker tableView:didSelectRowAtIndexPath:] + 1407 7 UIKit 0x0009b794 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1140 8 UIKit 0x00091d50 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219 9 Foundation 0x007937f6 __NSFireDelayedPerform + 441 10 CoreFoundation 0x00d9bfe3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19 11 CoreFoundation 0x00d9d594 __CFRunLoopDoTimer + 1220 12 CoreFoundation 0x00cf9cc9 __CFRunLoopRun + 1817 13 CoreFoundation 0x00cf9240 CFRunLoopRunSpecific + 208 14 CoreFoundation 0x00cf9161 CFRunLoopRunInMode + 97 15 GraphicsServices 0x0102e268 GSEventRunModal + 217 16 GraphicsServices 0x0102e32d GSEventRun + 115 17 UIKit 0x0003442e UIApplicationMain + 1160 18 Kiosk 0x0000239a main + 104 19 Kiosk 0x00002329 start + 53 ) terminate called after throwing an instance of 'NSException'

    Read the article

  • Multiple errors while adding searching to app

    - by Thijs
    Hi, I'm fairly new at iOS programming, but I managed to make a (in my opinion quite nice) app for the app store. The main function for my next update will be a search option for the app. I followed a tutorial I found on the internet and adapted it to fit my app. I got back quite some errors, most of which I managed to fix. But now I'm completely stuck and don't know what to do next. I know it's a lot to ask, but if anyone could take a look at the code underneath, it would be greatly appreciated. Thanks! // // RootViewController.m // GGZ info // // Created by Thijs Beckers on 29-12-10. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "RootViewController.h" // Always import the next level view controller header(s) #import "CourseCodes.h" @implementation RootViewController @synthesize dataForCurrentLevel, tableViewData; #pragma mark - #pragma mark View lifecycle // OVERRIDE METHOD - (void)viewDidLoad { [super viewDidLoad]; // Go get the data for the app... // Create a custom string that points to the right location in the app bundle NSString *pathToPlist = [[NSBundle mainBundle] pathForResource:@"SCSCurriculum" ofType:@"plist"]; // Now, place the result into the dictionary property // Note that we must retain it to keep it around dataForCurrentLevel = [[NSDictionary dictionaryWithContentsOfFile:pathToPlist] retain]; // Place the top level keys (the program codes) in an array for the table view // Note that we must retain it to keep it around // NSDictionary has a really useful instance method - allKeys // The allKeys method returns an array with all of the keys found in (this level of) a dictionary tableViewData = [[[dataForCurrentLevel allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] retain]; //Initialize the copy array. copyListOfItems = [[NSMutableArray alloc] init]; // Set the nav bar title self.title = @"GGZ info"; //Add the search bar self.tableView.tableHeaderView = searchBar; searchBar.autocorrectionType = UITextAutocorrectionTypeNo; searching = NO; letUserSelectRow = YES; } /* - (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]; } */ //RootViewController.m - (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar { searching = YES; letUserSelectRow = NO; self.tableView.scrollEnabled = NO; //Add the done button. self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneSearching_Clicked:)] autorelease]; } - (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { if(letUserSelectRow) return indexPath; else return nil; } //RootViewController.m - (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText { //Remove all objects first. [copyListOfItems removeAllObjects]; if([searchText length] &gt; 0) { searching = YES; letUserSelectRow = YES; self.tableView.scrollEnabled = YES; [self searchTableView]; } else { searching = NO; letUserSelectRow = NO; self.tableView.scrollEnabled = NO; } [self.tableView reloadData]; } //RootViewController.m - (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar { [self searchTableView]; } - (void) searchTableView { NSString *searchText = searchBar.text; NSMutableArray *searchArray = [[NSMutableArray alloc] init]; for (NSDictionary *dictionary in listOfItems) { NSArray *array = [dictionary objectForKey:@"Countries"]; [searchArray addObjectsFromArray:array]; } for (NSString *sTemp in searchArray) { NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch]; if (titleResultsRange.length &gt; 0) [copyListOfItems addObject:sTemp]; } [searchArray release]; searchArray = nil; } //RootViewController.m - (void) doneSearching_Clicked:(id)sender { searchBar.text = @""; [searchBar resignFirstResponder]; letUserSelectRow = YES; searching = NO; self.navigationItem.rightBarButtonItem = nil; self.tableView.scrollEnabled = YES; [self.tableView reloadData]; } //RootViewController.m - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { if (searching) return 1; else return [listOfItems count]; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (searching) return [copyListOfItems count]; else { //Number of rows it should expect should be based on the section NSDictionary *dictionary = [listOfItems objectAtIndex:section]; NSArray *array = [dictionary objectForKey:@"Countries"]; return [array count]; } } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { if(searching) return @""; if(section == 0) return @"Countries to visit"; else return @"Countries visited"; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... if(searching) cell.text = [copyListOfItems objectAtIndex:indexPath.row]; else { //First get the dictionary object NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; NSArray *array = [dictionary objectForKey:@"Countries"]; NSString *cellValue = [array objectAtIndex:indexPath.row]; cell.text = cellValue; } return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //Get the selected country NSString *selectedCountry = nil; if(searching) selectedCountry = [copyListOfItems objectAtIndex:indexPath.row]; else { NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; NSArray *array = [dictionary objectForKey:@"Countries"]; selectedCountry = [array objectAtIndex:indexPath.row]; } //Initialize the detail view controller and display it. DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]]; dvController.selectedCountry = selectedCountry; [self.navigationController pushViewController:dvController animated:YES]; [dvController release]; dvController = nil; } //RootViewController.m - (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar { //Add the overlay view. if(ovController == nil) ovController = [[OverlayViewController alloc] initWithNibName:@"OverlayView" bundle:[NSBundle mainBundle]]; CGFloat yaxis = self.navigationController.navigationBar.frame.size.height; CGFloat width = self.view.frame.size.width; CGFloat height = self.view.frame.size.height; //Parameters x = origion on x-axis, y = origon on y-axis. CGRect frame = CGRectMake(0, yaxis, width, height); ovController.view.frame = frame; ovController.view.backgroundColor = [UIColor grayColor]; ovController.view.alpha = 0.5; ovController.rvController = self; [self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view]; searching = YES; letUserSelectRow = NO; self.tableView.scrollEnabled = NO; //Add the done button. self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneSearching_Clicked:)] autorelease]; } // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations. return YES; } - (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 { [dataForCurrentLevel release]; [tableViewData release]; [super dealloc]; } #pragma mark - #pragma mark Table view methods // DATA SOURCE METHOD - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // DATA SOURCE METHOD - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // How many rows should be displayed? return [tableViewData count]; } // DELEGATE METHOD - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Cell reuse block static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell's contents - we want the program code, and a disclosure indicator cell.textLabel.text = [tableViewData objectAtIndex:indexPath.row]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } //RootViewController.m - (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText { //Remove all objects first. [copyListOfItems removeAllObjects]; if([searchText length] &gt; 0) { [ovController.view removeFromSuperview]; searching = YES; letUserSelectRow = YES; self.tableView.scrollEnabled = YES; [self searchTableView]; } else { [self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view]; searching = NO; letUserSelectRow = NO; self.tableView.scrollEnabled = NO; } [self.tableView reloadData]; } //RootViewController.m - (void) doneSearching_Clicked:(id)sender { searchBar.text = @""; [searchBar resignFirstResponder]; letUserSelectRow = YES; searching = NO; self.navigationItem.rightBarButtonItem = nil; self.tableView.scrollEnabled = YES; [ovController.view removeFromSuperview]; [ovController release]; ovController = nil; [self.tableView reloadData]; } // DELEGATE METHOD - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // In any navigation-based application, you follow the same pattern: // 1. Create an instance of the next-level view controller // 2. Configure that instance, with settings and data if necessary // 3. Push it on to the navigation stack // In this situation, the next level view controller is another table view // Therefore, we really don't need a nib file (do you see a CourseCodes.xib? no, there isn't one) // So, a UITableViewController offers an initializer that programmatically creates a view // 1. Create the next level view controller // ======================================== CourseCodes *nextVC = [[CourseCodes alloc] initWithStyle:UITableViewStylePlain]; // 2. Configure it... // ================== // It needs data from the dictionary - the "value" for the current "key" (that was tapped) NSDictionary *nextLevelDictionary = [dataForCurrentLevel objectForKey:[tableViewData objectAtIndex:indexPath.row]]; nextVC.dataForCurrentLevel = nextLevelDictionary; // Set the view title nextVC.title = [tableViewData objectAtIndex:indexPath.row]; // 3. Push it on to the navigation stack // ===================================== [self.navigationController pushViewController:nextVC animated:YES]; // Memory manage it [nextVC release]; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source. [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ @end

    Read the article

< Previous Page | 8 9 10 11 12