a specific instance of insertsubview at index not working in ios 6.0 - objective-c

I'm testing my ios app that has a deployment target of 5.0 and a base SDK of 6.1.
Everything works fine in ios 5.0, and ios 5.1, but in ios 6.0 I'm having an issue with inserting a subview at index. The subview is a tableview and the parent view is an uialertview that was created as a special class "UIAlertTableView." The alertview appears, but there appears to be nothing inserted. Before this, I had fixed an autorotation issue of the superview (which is in landscape) because, as it is well known ios 6.0 handles rotation differently, so now my superview appears correctly, but as I said, this alertview pops up with no table now. Am I suppose to be fixing autorotation issues for the tableview as well as the superview? I didn't think this would be necessary since the tableview is not declared in the imported class, is is declared within the parent viewcontroller. Or could this be because of some method that was deprecated in ios 6.0?
/*UIAlertTableView.m (the imported object class)*/
#interface UIAlertView (private)
- (void)layoutAnimated:(BOOL)fp8;
#end
#implementation UIAlertTableView
#synthesize tableWidth;
#synthesize tableHeight;
#synthesize lowestView;
#synthesize kTablePadding;
#synthesize alertDelegate;
- (void)layoutAnimated:(BOOL)fp8 {
[super layoutAnimated:fp8];
[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y - tableExtHeight/2, self.frame.size.width, self.frame.size.height + tableExtHeight)];
// We get the lowest non-control view (i.e. Labels) so we can place the table view just below
int i = 0;
while (![[self.subviews objectAtIndex:i] isKindOfClass:[UIControl class]]) {
lowestView = [self.subviews objectAtIndex:i];
i++;
}
tableWidth = 262.0f;
for (UIView *sv in self.subviews) {
// Move all Controls down
if ([sv isKindOfClass:[UIControl class]]) {
sv.frame = CGRectMake(sv.frame.origin.x, sv.frame.origin.y + tableExtHeight, sv.frame.size.width, sv.frame.size.height);
}
}
}
- (void)show{
[self prepare];
[super show];
}
- (void)prepare {
if (tableHeight == 0) {
tableHeight = 150.0f;
}
kTablePadding = 8.0f;
tableExtHeight = tableHeight + 2 * kTablePadding;
[self setNeedsLayout];
}
#end
/*the UIAlertTableView class is imported into the myViewController header file*/
/*myViewController.m*/
#implementation myViewController
#synthesize myTableView;
#synthesize alert;
#synthesize imageView;
#synthesize scrollView;
#synthesize models;
#synthesize picked;
#pragma myTableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [models count];
}
- (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];
}
// now configure the cell
cell.textLabel.text = [models objectAtIndex:[indexPath row]];
[cell setAccessibilityTraits: UIAccessibilityTraitButton];
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (returnedSetting && (indexPath.row == prevSelectedIndex)){
returnedSetting = FALSE;
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//index path to row that's selected
NSIndexPath *myIndexPath = [myTableView indexPathForSelectedRow];
UITableViewCell *cell = [myTableView cellForRowAtIndexPath:myIndexPath];
labelText = cell.textLabel.text;
selectedModel = cell.textLabel.text;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSIndexPath *myIndexPath = [tableView indexPathForSelectedRow];
prevSelectedIndex = myIndexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:myIndexPath];
[alert dismissWithClickedButtonIndex:0 animated:YES];
labelText = cell.textLabel.text;
selectedModel = cell.textLabel.text;
[self dismissModalViewControllerAnimated:YES];
}
-(void)removeButton{
[UIView animateWithDuration:1.5
delay:1.5
options:UIViewAnimationCurveEaseInOut
animations:^ {
eButton.alpha = 0;
}
completion:^(BOOL finished) {
}];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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)showAlertFor:(NSTimer *)timer{
[alert show];
myTableView.frame = CGRectMake(11.0f, alert.lowestView.frame.origin.y + alert.lowestView.frame.size.height + 2 * alert.kTablePadding, alert.tableWidth, alert.tableHeight);
[alert insertSubview:myTableView atIndex:1];
[myTableView performSelector:#selector(flashScrollIndicators) withObject:nil afterDelay:.3];
}
-(void)bringupAlertTableViewFor:(NSString *)dName atLocationOnScreen:(CGPoint)newPoint{
if (([dName isEqualToString:#"hello"]){
picked =TRUE;
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f) style:UITableViewStylePlain];
alert = [[UIAlertTableView alloc] initWithTitle:dName
message:#"Choose from the table below:"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert setDelegate: alert.alertDelegate];
models = [[NSMutableArray alloc]init];
myTableView.delegate = self;
myTableView.dataSource = self;
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"Decisions" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"dName == %#", dName];
[request setPredicate: predicate];
NSError *error;
//matches found
NSArray *matchingData = [context executeFetchRequest: request error: &error];
for (NSManagedObject *obj in matchingData) {
[models addObject:[NSString stringWithFormat:#"%#",[obj valueForKey: #"model"]]];
}
alert.tableHeight = 120;
[alert show];
myTableView.frame = CGRectMake(11.0f, alert.lowestView.frame.origin.y + alert.lowestView.frame.size.height + 2 * alert.kTablePadding, alert.tableWidth, alert.tableHeight);
[alert insertSubview:myTableView atIndex:1];
[myTableView performSelector:#selector(flashScrollIndicators) withObject:nil afterDelay:.3];
}else{
picked = TRUE;
frame.origin.x = newPoint.x - 29; // new x coordinate
frame.origin.y = 240; // new y coordinate
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 1.5];
[UIView commitAnimations];
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f) style:UITableViewStylePlain];
alert = [[UIAlertTableView alloc] initWithTitle:dName
message:#"Select a choice:"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert setDelegate: alert.alertDelegate];
models = [[NSMutableArray alloc]init];
myTableView.delegate = self;
myTableView.dataSource = self;
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"Decisions" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"deName == %#", dName];
[request setPredicate: predicate];
NSError *error;
//matches found
NSArray *matchingData = [context executeFetchRequest: request error: &error];
for (NSManagedObject *obj in matchingData) {
[models addObject:[NSString stringWithFormat:#"%#",[obj valueForKey: #"model"]]];
}
alert.tableHeight = 120;
[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:#selector(showAlertFor:) userInfo:nil repeats:NO];
previousPoint = newPoint;
}
}
-(IBAction)singleTapImageView:(UITapGestureRecognizer *)sender {
CGPoint pt = [sender locationInView: sender.view];
//find out which was pressed
if ( ((pt.x >= 52) && (pt.x <= 79)) && ((pt.y >= 269) && (pt.y <= 296))){
CGPoint newPoint = {45, (257 + 55)};
[self bringupAlertTableViewFor:#"Choice1" atLocationOnScreen:newPoint];
}
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)sView{
[self removeButton];
}
-(void)scrollViewDidScroll:(UIScrollView *)sView{
eButton.alpha = .7;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)sView
{
[self removeButton];
}
-(void)exitButtonPressed{
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
UIImage *imageS = [UIImage imageNamed:#"ti.png"];
imageView = [[TouchDetectingImageView alloc]initWithImage:imageS];
[imageView setDelegate:self];
imageView.frame = CGRectMake(20, 25, imageS.size.width,imageS.size.height);
CGFloat newScrollWidth = imageView.image.size.width + 20;
[scrollView setContentSize:(CGSizeMake(newScrollWidth, imageView.image.size.height))];
[scrollView addSubview: imageView];
imageView.contentMode = UIViewContentModeScaleToFill;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapImageView:)];
singleTap.numberOfTapsRequired = 1;
[scrollView addGestureRecognizer:singleTap];
UIImage *img = [UIImage imageNamed:#"backbutton.png"];
CGRect frameForButton = CGRectMake(0, 3, img.size.width, img.size.height);
eButton = [[exitButton alloc] initWithFrame:frameForButton];
[eButton setDelegate:self];
[eButton addTarget:self action:#selector(exitButtonPressed) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *buttonTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(exitButtonPressed)];
buttonTap.numberOfTapsRequired = 1;
[eButton addGestureRecognizer:buttonTap];
eButton.alpha = 0;
[self.view addSubview:eButton];
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewDidUnload
{
[self setScrollView:nil];
[self setImageView:nil];
[self setmyTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[scrollView flashScrollIndicators];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// The menu is only going to support landscape orientations
return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}
- (NSInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}
-(BOOL)shouldAutorotate{
return YES;
}
#end

The reason(s) for this were:
1) the call to layoutAnimated was being ignored
2) it appears that ios 6 handles view hierarchy somewhat differently...
3) ios 6.0 automatically scales to fit a 1136x640 display vs earlier version that scale to fit a 960x640 display.
solutions were:
use a layoutsubviews call and layoutifneeded
also using conditional statements to find the ios version (e.g. greater_than_or_equal_to ios 6.0)

Related

Set TV Menu Button To Go Back One Screen

My Apple TV app lists a collection of PDFs, and clicking one draws it on the screen. For some reason, though, it exits the app completely when someone hits the < / Menu button on the Apple TV Remote. What is going on to cause it to do that?
Up first is the code where it pulls up the list of all the PDFs, followed by the code for displaying the PDF.
-(void)viewDidLoad {
[super viewDidLoad];
self.definesPresentationContext = YES; // know where you want UISearchController to be displayed
}
- (void)viewWillAppear:(BOOL)animated {
if (self.searchControllerWasActive) {
self.searchController.active = self.searchControllerWasActive;
_searchControllerWasActive = NO;
if (self.searchControllerSearchFieldWasFirstResponder) {
[self.searchController.searchBar becomeFirstResponder];
_searchControllerSearchFieldWasFirstResponder = NO;
}
}
NSBundle *bundle = [NSBundle mainBundle];
self.files = [bundle pathsForResourcesOfType:#"pdf" inDirectory:#"AIMPDF"];
NSString *documentsDirectoryPath = [self.files objectAtIndex:thepath.row];
self.title = #"Devo Songs";
self.filenames = [[documentsDirectoryPath lastPathComponent] stringByDeletingPathExtension];
NSLog(#"%#", filenames);
NSMutableArray *names = [NSMutableArray arrayWithCapacity:[self.files count]];
for (NSString *path in self.files) {
[names addObject:[[path lastPathComponent] stringByDeletingPathExtension]];
}
self.files = names;
self.files = [names sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
self.tableView.backgroundColor = [UIColor whiteColor];
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"iphonebackground.png"]];
[super viewDidLoad];
[super viewWillAppear:animated];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
// update the filtered array based on the search text
NSString *searchText = searchController.searchBar.text;
NSMutableArray *searchResults2 = [self.files mutableCopy];
// strip out all the leading and trailing spaces
NSString *strippedString = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// break up the search terms (separated by spaces)
NSArray *searchItems = nil;
if (strippedString.length > 0) {
searchItems = [strippedString componentsSeparatedByString:#" "];
}
// build all the "AND" expressions for each value in the searchString
//
NSMutableArray *andMatchPredicates = [NSMutableArray array];
for (NSString *searchString in searchItems) {
NSPredicate *sPredicate =
[NSPredicate predicateWithFormat:#"SELF contains[c] %#", searchString];
[searchResults2 filterUsingPredicate:sPredicate];
// at this OR predicate to our master AND predicate
// NSCompoundPredicate *orMatchPredicates = [NSCompoundPredicate orPredicateWithSubpredicates:searchItemsPredicate];
//[andMatchPredicates addObject:orMatchPredicates];
}
// match up the fields of the Product object
// NSCompoundPredicate *finalCompoundPredicate =
//[NSCompoundPredicate andPredicateWithSubpredicates:andMatchPredicates];
//searchResults2 = [[searchResults filteredArrayUsingPredicate:finalCompoundPredicate] mutableCopy];
// hand over the filtered results to our search results table
APLResultsTableController *tableController = (APLResultsTableController *)self.searchController.searchResultsController;
tableController.filteredProducts = searchResults2;
[tableController.tableView reloadData];
}
- (void)handleSearchForTerm:(NSString *)searchTerm
{
[self setSavedSearchTerm:searchTerm];
if ([self searchResults] == nil)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[self setSearchResults:array];
array = nil;
}
[[self searchResults] removeAllObjects];
if ([[self savedSearchTerm] length] != 0)
{
for (NSString *currentString in [self files])
{
if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[[self searchResults] addObject:currentString];
}
}
}
}- (void)viewDidUnload
{
[super viewDidUnload];
// Save the state of the search UI so that it can be restored if the view is re-created.
[self setSavedSearchTerm:[[[self searchDisplayController] searchBar] text]];
[self setSearchResults:nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
// The device is an iPad running iPhone 3.2 or later.
return YES;
}
else
{
// The device is an iPhone or iPod touch.
return YES;
}
#else
// iPhone simulator
return YES;
#endif
}
#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.
NSInteger rows;
rows = [[self files] count];
return rows;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *filename = [[[self.files objectAtIndex:indexPath.row] lastPathComponent] stringByDeletingPathExtension];
NSInteger row = [indexPath row];
NSString *contentForThisRow = nil;
contentForThisRow = filename;
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
[[cell textLabel] setText:contentForThisRow];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica Neue" size:90];
cell.textLabel.textColor = [UIColor blackColor];
cell.backgroundColor = [UIColor lightGrayColor];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) {
return 80;
}
else {
return 120;
}
}
- (void)tableView:(UITableView *)tableView didUpdateFocusInContext:(UITableViewFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
//this gives you the indexpath of the focused cell
NSIndexPath *nextIndexPath = [context nextFocusedIndexPath];
NSLog(#"Do Something");
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.selectedCountry = (tableView == self.tableView) ?
self.files[indexPath.row] : self.resultsTableController.filteredProducts[indexPath.row];
[self performSegueWithIdentifier:#"ShowSong" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"ShowSong"])
{
NSLog(#"Selecting %#", self.selectedCountry);
FirstViewController* userViewController = [segue destinationViewController];
userViewController.selectedCountry = self.selectedCountry;
//if you need to pass data to the next controller do it here
}
}
#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)dealloc {
}
#end
And now the code for opening:
#implementation FirstViewController
- (CGPDFDocumentRef)openPDFLocal:(NSString *)pdfURL {
NSURL* NSUrl = [NSURL fileURLWithPath:pdfURL];
return [self openPDF:NSUrl];
}
- (CGPDFDocumentRef)openPDFURL:(NSString *)pdfURL {
NSURL* NSUrl= [NSURL URLWithString:pdfURL];
return [self openPDF:NSUrl];
}
- (CGPDFDocumentRef)openPDF:(NSURL*)NSUrl {
CFURLRef url = (CFURLRef)CFBridgingRetain(NSUrl);
CGPDFDocumentRef myDocument;
myDocument = CGPDFDocumentCreateWithURL(url);
if (myDocument == NULL) {
NSLog(#"can't open %#", NSUrl);
CFRelease (url);
return nil;
}
CFRelease (url);
if (CGPDFDocumentGetNumberOfPages(myDocument) == 0) {
CGPDFDocumentRelease(myDocument);
return nil;
}
return myDocument;
}
- (void)drawDocument:(CGPDFDocumentRef)pdfDocument
{
// Get the total number of pages for the whole PDF document
int totalPages= (int)CGPDFDocumentGetNumberOfPages(pdfDocument);
self.pages = totalPages;
NSMutableArray *pageImages = [[NSMutableArray alloc] init];
// Iterate through the pages and add each page image to an array
for (int i = 1; i <= totalPages; i++) {
// Get the first page of the PDF document
CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocument, i);
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
// Begin the image context with the page size
// Also get the grapgics context that we will draw to
UIGraphicsBeginImageContext(pageRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// Rotate the page, so it displays correctly
CGContextTranslateCTM(context, 0.0, pageRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, pageRect, 0, true));
// Draw to the graphics context
CGContextDrawPDFPage(context, page);
// Get an image of the graphics context
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[pageImages addObject:image];
}
// Set the image of the PDF to the current view
[self addImagesToScrollView:pageImages];
}
-(void)addImagesToScrollView:(NSMutableArray*)imageArray {
int heigth = 0;
for (UIImage *image in imageArray) {
UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
imgView.frame=CGRectMake(200, heigth, 1520, 1080);
[_scrollView addSubview:imgView];
heigth += imgView.frame.size.height;
}
}
-(void)viewDidLayoutSubviews {
NSLog(#"%ld", (long)self.pages);
_scrollView.contentSize = CGSizeMake(1920, 1080*self.pages);
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"DOCUMENTS%#", self.selectedCountry);
NSString *testing = [self.selectedCountry stringByAppendingString:#".pdf"];
//This is passed in from a tableview after selecting the PDF needed.
_scrollView.panGestureRecognizer.allowedTouchTypes = #[ #(UITouchTypeIndirect) ];
NSString *Documents = [[NSBundle mainBundle] pathForResource:self.selectedCountry ofType:#"pdf" inDirectory:#"AIMPDF"];
NSLog(#"OKOKOK%#", Documents);
NSURL *url = [NSURL fileURLWithPath:Documents];
self.view.backgroundColor = [UIColor blackColor];
CGPDFDocumentRef pdfDocument = [self openPDF:url];
[self drawDocument:pdfDocument];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
In your case the searching view controller stays on the top level of your app that's why the app is closed by pressing Menu button instead of returning to your start screen. On tvOS you should not use UISearchController directly and call
[self.searchController.searchBar becomeFirstResponder]; or self.searchController.active = YES; to present searching because it breaks a stacked view hierarchy that allows you to navigate upper by presented view controllers.
On Apple TV, people typically navigate by moving through stacked screens of content. Each screen may present entry points to other screens, and provides a way — through the remote — to return to the previous screen or main menu.
https://developer.apple.com/design/human-interface-guidelines/tvos/app-architecture/navigation/
There is UISearchContainerViewController view controller that manages the presentation of search results in your interface and you can use it for searching:
In tvOS, rather than push a UISearchController onto a navigation controller’s stack or use one as a child of another container view controller, embed an instance of this class and let it manage the presentation of the search controller’s content. https://developer.apple.com/documentation/uikit/uisearchcontainerviewcontroller
For instance:
UITableViewController* searchTableViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"SearchTableViewController"];
UISearchController* searchController = [[UISearchController alloc] initWithSearchResultsController:searchTableViewController];
searchController.delegate = self;
searchController.searchResultsUpdater = self;
searchController.searchBar.delegate = self;
self.searchContainerViewController = [[UISearchContainerViewController alloc] initWithSearchController:searchController];
// Show searching
[self presentViewController:self.searchContainerViewController animated:YES completion:nil];

UITableViewController application crashes

The UITableViewController freezes when scrolling or when viewDidAppear:. I see that when the problem starts, the app start to allocate objects uncontrollably.
I have the following project for iOS: basically download information from CoreData, but when I go to display the data in the table, the application freezes (both the device and the simulator). But if I show the arrangement in a downloaded NSLog no errors. The code is as follows:
I see that when the problem starts, the app start to allocate objects uncontrollably.
The UITableViewController freezes when scrolling or when viewDidAppear:
TableViewController.h
#interface Set_ScheduleViewController : UITableViewController
{
STCore *core;
UILabel *label;
NSArray *objects;
}
#end
TableViewController.m:
#implementation Set_ScheduleViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
core = [[STCore alloc] init];
[super viewDidLoad];
// 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)reloadData
{
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
objects = [core getAllClassesUsingSortDescriptions:#[sort]];
[[self tableView] reloadData];
}
- (void)viewDidAppear:(BOOL)animated
{
[self reloadData];
[super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [objects count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 20)];
label.textColor = [UIColor colorWithHex:0x88B6DB];
label.font = [UIFont systemFontOfSize:12.0f];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentRight;
label.minimumFontSize = 12.0f;
tableView.separatorColor = [UIColor colorWithHex:0xDAE1E6];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor colorWithHex:0x393B40];
cell.textLabel.font = [UIFont boldSystemFontOfSize:16.0f];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.textColor = [UIColor colorWithHex:0x393B40];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12.0f];
}
cell.textLabel.text = [[objects objectAtIndex:indexPath.row] name];
cell.detailTextLabel.text = [[objects objectAtIndex:indexPath.row] location];
STMultipleDate *dates = [STMultipleDate new];
for (Schedule *sch in [[objects objectAtIndex:indexPath.row] schedule]) {
STDate *date = [STDate new];
[date setWeekday:[[sch day] integerValue]];
[date setHour:[[sch hour] integerValue]];
[date setMinutes:[[sch minutes] integerValue]];
[dates addDate:date];
}
label.text = [STCore splitDates:dates];
cell.accessoryView = label;
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
if ([objects count] < 1) {
return NSLocalizedString(#"SETSCH_FOOTER_DEFAULT_404", #"");
}
return nil;
}
STCore.m
- (NSArray *)getAllClassesUsingSortDescriptions:(NSArray *)descs
{
if (![self isReady]) {
return #[];
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Classes" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:descs];
NSError *error;
NSArray *returned = [_context executeFetchRequest:fetchRequest error:&error];
if (error) {
[_delegate core:self didRecivedAnError:error];
}
return returned;
}
In your viewDidLoad you're locking the context with [[core context] lock];, which is causing your getAllClassesUsingSortDescriptions to wait for the lock to clear. Remove the lock.

UInavigationbar and super dealloc causing app crash

I am having a application crash when i use back button in UINavigation child and child [supper dealloc] called application get crash. I tried but i am not able to find any error. Instrument saying below issue but i am not getting the point here
# Address Category Event Type RefCt Timestamp Size Responsible Library Responsible Caller
0 0x9e8c8c0 CALayer Malloc 1 00:05.082.180 48 UIKit -[UIView _createLayerWithFrame:]
1 0x9e8c8c0 CALayer Zombie -1 00:18.855.037 0 QuartzCore CA::release_objects(X::List<void const*>*)
if you can help me i will be great thankfull to you.
Here is the root page code
//
// TNTScenarioViewController.m
// TurfNutritionTool
//
// Created by Aashish Joshi on 10/20/11.
// Copyright 2011 Abacus Consultancy Services. All rights reserved.
//
#import "TNTScenarioViewController.h"
#import "ScenarioDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation TNTScenarioViewController
#synthesize scenarioTable = _scenarioTable;
#synthesize scenarioDetail = _scenarioDetail;
#synthesize scenarioId = _scenarioId;
#synthesize scenarioTableCellStyle = _scenarioTableCellStyle;
#synthesize dbObject = _dbObject;
#synthesize headerDateLabel = _headerDateLabel;
#synthesize headerTurfAcresLabel = _headerTurfAcresLabel;
#synthesize headerScenarioIDLabel = _headerScenarioIDLabel;
#synthesize headerDescriptionLabel = _headerDescriptionLabel;
#synthesize headerProductTypeLabel = _headerProductTypeLabel;
#synthesize headerTargetNitrogenLabel = _headerTargetNitrogenLabel;
#synthesize headerView = _headerView;
#synthesize synchronize = _synchronize;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"main_login_bg.png"]];
self.view.backgroundColor = _background;
[_background release];
_scenarioTable.delegate = self;
_scenarioTable.dataSource = self;
// Set the table view to be rounded
[[self.scenarioTable layer] setCornerRadius:5.0];
[self loadDBAccessDatabase];
// [self didApplicationLaunchedFirstTime];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIToolbar* _rightNavBarTools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 260, 44)];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* _rightNavBarButtons = [[NSMutableArray alloc] initWithCapacity:4];
UIBarButtonItem *_signout = [[UIBarButtonItem alloc] initWithTitle:#"Sign out" style:UIBarButtonItemStyleBordered target:self action:#selector(didApplicationLaunchedFirstTime)];
[_rightNavBarButtons addObject:_signout];
[_signout release];
UIBarButtonItem *_syncronize = [[UIBarButtonItem alloc] initWithTitle:#"Synchronize" style:UIBarButtonItemStyleBordered target:self action:#selector(syncronize)];
[_rightNavBarButtons addObject:_syncronize];
[_syncronize release];
UIBarButtonItem *_addNewScenario = [[UIBarButtonItem alloc]
initWithTitle:#"New TNT" style:UIBarButtonItemStyleBordered target:self
action:#selector(startNewScenario)];
[_rightNavBarButtons addObject:_addNewScenario];
[_addNewScenario release];
[_rightNavBarTools setItems:_rightNavBarButtons animated:NO];
[_rightNavBarButtons release];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:_rightNavBarTools] autorelease];
[_rightNavBarTools release];
[self loadAllScenario];
}
- (void)viewWillAppear:(BOOL)animated
{
NSLog(#"%d", [self retainCount]);
[super viewWillAppear:animated];
[self loadAllScenario];
[self.scenarioTable reloadData];
}
- (void)viewDidUnload
{
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return [self.scenarioId count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"scenarioTableCellStyle" owner:self options:nil];
cell = self.scenarioTableCellStyle;
self.scenarioTableCellStyle = nil;
}
if (indexPath.row % 2 == 0) {
cell.contentView.backgroundColor = [UIColor colorWithWhite:253.0/255 alpha:1];
} else {
cell.contentView.backgroundColor = [UIColor colorWithWhite:250.0/255 alpha:1];
}
NSDictionary * _scenarioDetailRow = [self.dbObject getScenarioDetail:[self.scenarioId objectAtIndex:indexPath.row]];
NSNumber* _tempNumber;
NSNumberFormatter* _formatter = [[NSNumberFormatter alloc] init];
NSString* _convertedNumber;
// Configure the cell...
_tempNumber = [_scenarioDetailRow objectForKey:#"scenarioid"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
UILabel* _label = (UILabel *)[cell viewWithTag:1];
_label.text = _convertedNumber;
_label = (UILabel *)[cell viewWithTag:2];
NSString* _turftype = [_scenarioDetailRow objectForKey:#"turf"];
_label.text = _turftype;
_label = (UILabel *)[cell viewWithTag:3];
_tempNumber = [_scenarioDetailRow objectForKey:#"targetnitrogen"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
_label.text = _convertedNumber;
_label = (UILabel *)[cell viewWithTag:4];
_tempNumber = [_scenarioDetailRow objectForKey:#"turfacre"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
_label.text = _convertedNumber;
[_formatter release];
_label = (UILabel *)[cell viewWithTag:5];
NSString* _dateCreated = [_scenarioDetailRow objectForKey:#"datecreated"];
NSDateFormatter *inputFormatter = [[[NSDateFormatter alloc] init] autorelease];
[inputFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *_inputDateCreated = [inputFormatter dateFromString:_dateCreated];
NSDateFormatter *outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
[outputFormatter setDateFormat:#"MM-dd-yyyy"];
NSString *_outputDateCreated = [outputFormatter stringFromDate:_inputDateCreated];
_label.text = _outputDateCreated;
_label = (UILabel *)[cell viewWithTag:6];
if (([_scenarioDetailRow objectForKey:#"description"] != nil) && ([_scenarioDetailRow objectForKey:#"description"] != (id)[NSNull null])){
NSString* _discription = [_scenarioDetailRow objectForKey:#"description"];
_label.text = _discription;
} else {
_label.text = [NSString stringWithString:#""];
}
return cell;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
if (UIInterfaceOrientationIsLandscape(fromInterfaceOrientation))
{
// Move the plots into place for portrait
_headerScenarioIDLabel.frame = CGRectMake(-30, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(52, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(278, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(368, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(437, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(545, 2, 125, 20);
}
else
{
// Move the plots into place for landscape
_headerScenarioIDLabel.frame = CGRectMake(-26, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(85, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(390, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(526, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(626, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(759, 2, 125, 20);
}
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
_headerScenarioIDLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerDateLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerDescriptionLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerProductTypeLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerTargetNitrogenLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerTurfAcresLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
BOOL isLandscape = UIDeviceOrientationIsLandscape(self.interfaceOrientation);
if (UIInterfaceOrientationIsLandscape(orientation) || isLandscape)
{
// Move the plots into place for landscape
_headerScenarioIDLabel.frame = CGRectMake(-26, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(85, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(390, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(526, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(626, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(759, 2, 125, 20);
}
else
{
// Move the plots into place for portrait
_headerScenarioIDLabel.frame = CGRectMake(-30, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(52, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(278, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(368, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(437, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(545, 2, 125, 20);
}
if(_headerView == nil) {
//allocate the view if it doesn't exist yet
_headerView = [[UIView alloc] init];
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"toolbar_bkg.png"]];
_headerView.backgroundColor = _background;
[_background release];
_headerScenarioIDLabel.backgroundColor = [UIColor clearColor];
_headerScenarioIDLabel.opaque = NO;
_headerScenarioIDLabel.textColor = [UIColor whiteColor];
_headerScenarioIDLabel.font = [UIFont boldSystemFontOfSize:12];
_headerScenarioIDLabel.textAlignment = UITextAlignmentCenter;
_headerScenarioIDLabel.text = #"ID";
_headerDateLabel.backgroundColor = [UIColor clearColor];
_headerDateLabel.opaque = NO;
_headerDateLabel.textColor = [UIColor whiteColor];
_headerDateLabel.font = [UIFont boldSystemFontOfSize:12];
_headerDateLabel.textAlignment = UITextAlignmentCenter;
_headerDateLabel.text = #"Date";
_headerDescriptionLabel.backgroundColor = [UIColor clearColor];
_headerDescriptionLabel.opaque = NO;
_headerDescriptionLabel.textColor = [UIColor whiteColor];
_headerDescriptionLabel.font = [UIFont boldSystemFontOfSize:12];
_headerDescriptionLabel.textAlignment = UITextAlignmentCenter;
_headerDescriptionLabel.text = #"Description";
_headerProductTypeLabel.backgroundColor = [UIColor clearColor];
_headerProductTypeLabel.opaque = NO;
_headerProductTypeLabel.textColor = [UIColor whiteColor];
_headerProductTypeLabel.font = [UIFont boldSystemFontOfSize:12];
_headerProductTypeLabel.textAlignment = UITextAlignmentCenter;
_headerProductTypeLabel.text = #"Product Type";
_headerTargetNitrogenLabel.backgroundColor = [UIColor clearColor];
_headerTargetNitrogenLabel.opaque = NO;
_headerTargetNitrogenLabel.textColor = [UIColor whiteColor];
_headerTargetNitrogenLabel.font = [UIFont boldSystemFontOfSize:12];
_headerTargetNitrogenLabel.textAlignment = UITextAlignmentCenter;
_headerTargetNitrogenLabel.text = #"Target N";
_headerTurfAcresLabel.backgroundColor = [UIColor clearColor];
_headerTurfAcresLabel.opaque = NO;
_headerTurfAcresLabel.textColor = [UIColor whiteColor];
_headerTurfAcresLabel.font = [UIFont boldSystemFontOfSize:12];
_headerTurfAcresLabel.textAlignment = UITextAlignmentCenter;
_headerTurfAcresLabel.text = #"Turf Acres";
//add the button to the view
[_headerView addSubview:_headerScenarioIDLabel];
[_headerView addSubview:_headerDescriptionLabel];
[_headerView addSubview:_headerProductTypeLabel];
[_headerView addSubview:_headerTargetNitrogenLabel];
[_headerView addSubview:_headerTurfAcresLabel];
[_headerView addSubview:_headerDateLabel];
}
//return the view for the footer
return _headerView;
}
// specify the height of your footer section
- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
//differ between your sections or if you
//have only on section return a static value
return 24;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForFooterInSection:(NSInteger)section {
//differ between your sections or if you
//have only on section return a static value
return 14;
}
- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"toolbar_bkg.png"]];
UIView* _customView = [[[UIView alloc]initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)]autorelease];
_customView.backgroundColor = _background;
[_background release];
return _customView;
}
/*
// 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;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
_detailViewController.dbObject = self.dbObject;
[_detailViewController setScenarioId:[self.scenarioId objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:_detailViewController animated:YES];
[_detailViewController release];
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
// Updates the appearance of the Edit|Done button as necessary.
[super setEditing:editing animated:animated];
[self.scenarioTable setEditing:editing animated:YES];
// Disable the add button while editing.
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// must update the database before updating the tableView
// so that the tableView never has a row that's missing from the database
[self.dbObject deleteScenarioRow:[self.scenarioId objectAtIndex:indexPath.row]];
[self loadAllScenario];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.scenarioTable reloadData];
}
}
- (void)dealloc {
[_synchronize release];
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
[_headerDateLabel release];
[_headerTurfAcresLabel release];
[_headerScenarioIDLabel release];
[_headerDescriptionLabel release];
[_headerProductTypeLabel release];
[_headerTargetNitrogenLabel release];
[_headerView release];
[super dealloc];
}
// Called when an alertview button is touched
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0:
{
NSLog(#"user not want to sync");
}
break;
case 1:
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
_synchronize = [[TNSynchronize alloc] init];
_synchronize.delegate = self;
[_synchronize jesonRequest];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
break;
}
}
- (void) reloadAfterSyncronize {
[self loadAllScenario];
[self.scenarioTable reloadData];
}
#pragma mark - TNTScenarioViewController lifecycle methods
- (void) syncronize {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Syncronize process", nil)
message:NSLocalizedString(#"\n Syncronize process will be start and work in background.", nil)
delegate:self
cancelButtonTitle:NSLocalizedString(#"Cancel", nil)
otherButtonTitles:NSLocalizedString(#"Ok", nil), nil];
[alert show];
[alert release];
}
- (void) didApplicationLaunchedFirstTime {
LoginViewController *loginViewObj = [[[LoginViewController alloc] init] autorelease];
loginViewObj.dbObject = self.dbObject;
UINavigationController *navigationController = [[[UINavigationController alloc]
initWithRootViewController:loginViewObj] autorelease];
navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentModalViewController:navigationController animated:YES];
}
- (void)loadSynchronizeController {
[self.scenarioTable reloadData];
}
// This is Method to New Scenario
- (void) startNewScenario {
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
[_detailViewController setScenarioId:[NSNumber numberWithInt:0]];
[self.navigationController pushViewController:_detailViewController animated:YES];
// [_detailViewController release];
}
// This Method use for Load Value of Scenario
- (NSMutableArray *) loadAllScenario {
// NSLog(#"%s", __FUNCTION__);
// First, test for existence.
NSArray* _paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* _documentsDirectory = [_paths objectAtIndex:0];
NSString* _writableConfigPath = [_documentsDirectory stringByAppendingPathComponent:#"Configuration.plist"];
NSMutableDictionary* _configFile = [[NSMutableDictionary alloc] initWithContentsOfFile:_writableConfigPath];
NSString* _loginStatus= [NSString stringWithString:[_configFile objectForKey:#"UserEmail"]];
[_configFile autorelease];
[self.scenarioId removeAllObjects];
if (!_dbObject) [self loadDBAccessDatabase];
self.scenarioId = [NSMutableArray arrayWithArray:[_dbObject getRelatedScenarioArray:_loginStatus]];
return self.scenarioId;
}
- (NSArray *) loadScenarioIDsIfEmpty {
// NSLog(#"%s", __FUNCTION__);
// First, test for existence.
NSArray* _paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* _documentsDirectory = [_paths objectAtIndex:0];
NSString* _writableConfigPath = [_documentsDirectory stringByAppendingPathComponent:#"Configuration.plist"];
NSMutableDictionary* _configFile = [[NSMutableDictionary alloc] initWithContentsOfFile:_writableConfigPath];
NSString* _loginStatus = [NSString stringWithString:[_configFile objectForKey:#"UserEmail"]];
[_configFile autorelease];
if (!_dbObject) [self loadDBAccessDatabase];
if (!self.scenarioId || ![self.scenarioId count]) self.scenarioId = [NSMutableArray arrayWithArray:[_dbObject getRelatedScenarioArray:_loginStatus]];
return self.scenarioId;
}
- (DBAccess *) loadDBAccessDatabase {
// NSLog(#"%s", __FUNCTION__);
_dbObject = [DBAccess sharedDBObjectAccess];
return _dbObject;
}
#end
This is the dealloc method as you asked
- (void)dealloc {
[_scenarioProductTable release];
[_attributePopover release];
[_gotMapRegion release];
[_gotTargetN release];
[_gotTurfAcres release];
[_gotTurftype release];
[_scenarioId release];
[_granularProductData release];
[_liquidProductData release];
[_areaGraphData release];
[_scenarioAppId release];
[_scenarioProductTableCellStyle release];
[_scenarioProductTable release];
[_carryOver release];
[_tempDiscription release];
[_scenarioDetailRow release];
[_turfacresTextField release];
[_discriptionTextField release];
[_footerView release];
[_headerView release];
[selectedTurftypeLabel release];
[selectedTargetNLabel release];
[selectedMapregionLabel release];
[selectedTurfAcresLabel release];
[_loginUser release];
[super dealloc];
}
and in this function it saying that i have the issue
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
_detailViewController.dbObject = self.dbObject;
[_detailViewController setScenarioId:[self.scenarioId objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:_detailViewController animated:YES];
[_detailViewController release];
}
and this line have 100% blame in the funnction
[self.navigationController pushViewController:_detailViewController animated:YES];
From the crash report, it is apparent that you are overreleasing an object (notice where it says the zombie CALayer has a retain count of -1; anything less than 0 is overreleased). My suggestion is either scour your code until you find it, use the Instruments tool 'Zombies' (which only works when profiling on the Simulator), or upgrade your project to ARC.
I would definitely recommend upgrading to ARC as the best choice. ARC streamlines your code and lowers your peak memory footprint, improving efficiency and greatly reducing the chances of a crash.
Edit:
To upgrade to ARC: (from the Xcode menu)
Edit -> Refactor -> Convert to Objective-C ARC...
(from Apple's Face Detection example project)
Edit 2:
In response to #Chris's answer:
In viewDidUnload you should only release objects that are created in viewDidLoad; also, you should usually only be setting IBOutlets to nil. For every time viewDidUnload is called, viewDidLoad will be called to recreate everything that was destroyed in viewDidUnload. So the lesson is in viewDidUnload, only nil out objects that are created in viewDidLoad. If you release something that isn't created in viewDidLoad, it won't be recreated when you return to that view, which can cause a crash.
Yet I don't think that is your problem here. viewDidUnload is not actually called when a view controller is destroyed (dealloc is called because the controller was popped from the navigation stack or the modal view controller was dismissed). viewDidUnload is only called when the application receives a memory warning- viewDidUnload's job is to release any objects that can be recreated later. Assuming you don't receive any memory warnings and you are just pushing/popping a view controller from the stack, the double release is viewDidUnload is not causing this problem (though it might cause one later).
Moral of the story:
Use ARC. It's not a toy, it really works. It won't 'lessen' your control over memory management- it removes the need for it. Apart from retain cycles (Brad Larson gives a nice explanation here: What kind of leaks does automatic reference counting in Objective-C not prevent or minimize?), ARC will take care of just about all of your memory management, especially leaks. You can still get rid of an object with:
someObject = nil;
so you can still control your memory footprint. #autoreleasepools are also still an option with ARC.
So, final moral of the story:
Use ARC.
- (void)viewDidUnload
{
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
Your -viewDidUnload method is double-releasing. First you explicitly release objects by referencing their instance variables, ie: [_scenarioTable release];. But you don't set the ivar to nil after doing that. So those instance variables still point to released objects.
Then you set the properties which are backed by those instance variables to nil. The properties are probably declared as using the retain memory management strategy. This means when you do self.scenarioTable = nil;, it will release the ivar associated with the property.
To fix this, just get rid of the 4 release calls at the top.
- (void)viewDidUnload
{
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
}
If you really want to keep those, change it to this:
- (void)viewDidUnload
{
[_scenarioTable release]; _scenarioTable = nil;
[_scenarioDetail release]; _scenarioDetail = nil;
[_scenarioId release]; _scenarioId = nil;
[_scenarioTableCellStyle release]; _scenarioTableCellStyle = nil;
[super viewDidUnload];
}
And this is why -viewDidUnload is deprecated in iOS 6.
like Rickay said, in your dealloc method and your viewDidUnload you release your 4 scenario objects twice. I've only used ARC but I'm pretty sure thats your issue

Playing video in iPhone simulator with Media Player Framework

I am giving my entire code below if that helps anyway.....
#import "ContentViewController.h"
#import "ContentViewController.h"
#import "MediaPlayerViewController.h"
#import "TwitterViewController.h"
#import "YoutubeViewController.h"
#implementation ContentViewController
#synthesize imageView;
#synthesize imageView1;
#synthesize tableView;
#synthesize navigationController;
#synthesize toolBar;
#synthesize item;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - XMLParser Delegate
-(void)parseXMLFileAtURL:(NSString *)URL{
NSURL *xmlURL = [NSURL URLWithString:URL];
rssParser = [[NSXMLParser alloc]initWithContentsOfURL:xmlURL];
[rssParser setDelegate:self];
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
NSLog(#"Parsed");
}
-(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(#"Found file and started parsing");
}
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSString *errorString = [NSString stringWithFormat:#"Unable to download feed from website (Error Code %i)", [parseError code]];
NSLog(#"Error parsing xml: %#", errorString);
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"channel"]) {
rssElement = [[NSMutableDictionary alloc]init];
title = [[NSMutableString alloc]init];
link = [[NSMutableString alloc]init];
description = [[NSMutableString alloc]init];
copyright = [[NSMutableString alloc]init];
}
}
-(void)parser: (NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"channel"]) {
[rssElement setObject:title forKey:#"title"];
[rssElement setObject:link forKey:#"link"];
[rssElement setObject:description forKey:#"description"];
[rssElement setObject:copyright forKey:#"copyright"];
[item addObject:[rssElement copy]];
NSLog(#"adding stories %#", title);
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:#"title"]) {
[title appendString:string];
}else if ([currentElement isEqualToString:#"link"]) {
[link appendString:string];
}else if ([currentElement isEqualToString:#"description"]) {
[description appendString:string];
}else if ([currentElement isEqualToString:#"copyright"]) {
[copyright appendString:string];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(#"all done");
NSLog(#"item array has %d items", [item count]);
[tableView reloadData];
NSLog(#"Finished Parsing");
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
/* Add Segmented Controller */
if (segmentedControl == nil) {
segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:#"Video", #"Images", #"Audio", nil]];
}
[segmentedControl setFrame:CGRectMake(55.0, 47.0, 180.0, 31.0)];
[segmentedControl setSegmentedControlStyle:UISegmentedControlStyleBar];
[segmentedControl setWidth:70.0 forSegmentAtIndex:0];
[segmentedControl setWidth:70.0 forSegmentAtIndex:1];
[segmentedControl setWidth:70.0 forSegmentAtIndex:2];
[segmentedControl addTarget:self
action:#selector(segmentClick:)
forControlEvents:UIControlEventValueChanged];
[segmentedControl setMomentary:YES];
// [[[segmentedControl subviews]objectAtIndex:0]setTintColor:[UIColor blackColor]];
[self.view addSubview:segmentedControl];
/* Add Image View */
imageView1.image = [UIImage imageNamed:#"Harry.png"];
/* Add Page Control */
pageControl = [[UIPageControl alloc] init];
pageControl.frame = CGRectMake(120.0, 250.0, 100.0 ,10.0);
pageControl.numberOfPages = 5;
pageControl.currentPage = 0;
[self.view addSubview:pageControl];
/* Customize Table View */
tableView.backgroundColor = [UIColor clearColor];
imageView.image = [UIImage imageNamed:#"gradientBackground.png"];
item = [[NSMutableArray alloc]init];
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Video";
[self parseXMLFileAtURL:path];
[tableView reloadData];
NSLog(#"Returned %#", item);
}
headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(10.0, 270.0, 300.0, 14.0)];
headerLabel.text = #"Latest Videos";
headerLabel.textColor = [UIColor whiteColor];
headerLabel.backgroundColor = [UIColor clearColor];
[self.view addSubview:headerLabel];
}
/* Assign control to Segment Controller */
-(void)segmentClick:(UISegmentedControl *)segmentControl {
if (segmentControl.selectedSegmentIndex == 1){
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Image";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Images";
NSLog(#"Returned %#",item);
}
}
else if (segmentedControl.selectedSegmentIndex == 2){
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Audio";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Audios";
NSLog(#"Returned no items");
// [[[segmentedControl subviews]objectAtIndex:2]setTintColor:[UIColor blackColor]];
}
}
else {
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Video";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Videos";
NSLog(#"Returned %#", item);
}
// [[[segmentedControl subviews]objectAtIndex:0]setTintColor:[UIColor blackColor]];
}
}
#pragma mark Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"this is returned %#", item);
return item.count;
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
int feed = [indexPath indexAtPosition:[indexPath length] - 1];
cell.textLabel.text = [[item objectAtIndex:feed]objectForKey:#"title"];
cell.detailTextLabel.text = [[item objectAtIndex:feed]objectForKey:#"description"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *moviePath = [self.item objectAtIndex:indexPath.row];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
NSLog(#"Item has %#", movieURL);
playerController = [[MPMoviePlayerController alloc]initWithContentURL:movieURL];
[playerController play];
// MediaPlayerViewController *mediaView = [[MediaPlayerViewController alloc]initWithNibName:#"MediaPlayerViewController" bundle:nil];
// [self presentModalViewController:mediaView animated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
shareAlert = [[UIActionSheet alloc]initWithTitle:#"Share to" delegate:self cancelButtonTitle:#"Cancel"
destructiveButtonTitle:#"Facebook" otherButtonTitles:#"Twitter", nil];
[shareAlert showInView:self.view];
}
else if (buttonIndex == 1){
NSLog(#"button 2");
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) {
TwitterViewController *twitterController = [[TwitterViewController alloc]initWithNibName:#"TwitterViewController" bundle:nil];
[self presentModalViewController:twitterController animated:YES];
}
}
-(void)moviePlayBackDidFinish:(NSNotification *)notification{
MPMoviePlayerController *moviePlayerController = [notification object];
[moviePlayerController.view removeFromSuperview];
[moviePlayerController release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Changed didSelectRow method like following:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
moviePath = [[item objectAtIndex:indexPath.row]objectForKey:#"link"];
NSLog(#"moviepath has %#", moviePath);
movieURL = [NSURL URLWithString:moviePath];
NSLog(#"movieURL has %#", movieURL);
viewController = [[MPMoviePlayerViewController alloc]initWithContentURL:movieURL];
[self presentMoviePlayerViewControllerAnimated:viewController];
viewController.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
[playerController play];
viewController = nil;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:viewController];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
viewController = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:viewController];
if ([viewController respondsToSelector:#selector(setFullscreen:animated:)])
{
[viewController.view removeFromSuperview];
}
}
Now, on selecting any row a blank screen is coming and the application gets stuck there. Video is not played
Any help in this regard is appreciated.
Thanks in advance.
By looking at you code what i can tell you is that you dont have to reallocate your item object.
If you have allocated your item object somewhere in the class and stored the values in it then do not reallocate it again as you did here:
item = [[NSMutableArray alloc]init];
NSString *moviePath = [item objectAtIndex:indexPath.row];
by reallocating it you are allocating a new memory to it and in the new memory there is no objects present.
you are allocating new memory to your array by : item = [[NSMutableArray alloc]init]; . It means NO objects in it right now. And you are trying to access it by NSString *moviePath = [item objectAtIndex:indexPath.row]; where there is NO object at indexPath.row thats why it crashed.
There was actually nothing wrong with the code for playing video. The error was in the code for parsing and retrieving the rss feed which eventually was giving me wrong names of the videos. hence, videos were not playing.
The parsing code is Parsing attributes with same name but in different fields in iOS

pushViewController:detail not pushing detailView

I had my app navigating views perfectly. Now, for some reason that I can't figure out, my detailView is not presenting on the pushViewController:detail method in my modal view.
I cannot figure out why it's not working any more. Any help would be appreciated. Thanks.
Here's the method:
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == 0){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 1){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 2){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 3){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 4){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
}
Here's the class code. I'm not sure if I need to pass in a navigationController with modalView:
//
// ModalView.m
// DiningLog
//
// Created by Eric Rea on 10/10/11.
// Copyright 2011 Avid. All rights reserved.
//
#import "ModalView.h"
#import "DetailView.h"
#implementation ModalView
#synthesize tableView, excersizeName, numSets, time, restTime, dateFormatter, rating, excersizeArray, plistArray, numberWithBool;
-(IBAction) cancel:(id)sender{
[self dismissModalViewControllerAnimated:YES];
}
-(IBAction) save:(id)sender{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"ExcersizeList.plist"];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:#"Excersizes" ofType:#"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property list into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
// assign values
self.plistArray = [NSMutableArray arrayWithArray:[temp objectForKey:#"Excersizes"]];
NSLog(#"The contents of plistArray is%#", plistArray);
// set the variables to the values in the text fields
self.excersizeArray = [[NSMutableArray alloc] initWithCapacity:4];
[excersizeArray addObject:excersizeName];
[excersizeArray addObject:numSets];
[excersizeArray addObject:time];
[excersizeArray addObject:restTime];
[plistArray addObject:excersizeArray];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: plistArray, nil] forKeys:[NSArray arrayWithObjects: #"Excersizes", nil]];
NSString *error = nil;
// create NSData from dictionary
// NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistDict)
{
// write plistData to our Data.plist file
[plistDict writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
[self dismissModalViewControllerAnimated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tView {
// Return the number of sections.
return 1;
}
-(void)setObject:(id)object forNum:(int)num{
if(num == 0){
self.excersizeName = object;
NSLog(#"res %#", self.excersizeName);
}else if(num == 1){
self.numSets = object;
NSLog(#"res %#", self.numSets);
}else if(num == 2){
self.time = object;
NSLog(#"res %#", self.time);
}else if(num == 3){
self.restTime = object;
NSLog(#"res %#", self.restTime);
}else if(num == 4){
self.rating = [object floatValue];
}
[tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 5;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.row == 0){
cell.textLabel.text = #"Excersize";
cell.detailTextLabel.text = excersizeName;
}
if(indexPath.row == 1){
cell.textLabel.text = #"Sets";
cell.detailTextLabel.text = numSets;
}
if(indexPath.row == 2){
cell.textLabel.text = #"Time";
cell.detailTextLabel.text = time;
}
if(indexPath.row == 3){
cell.textLabel.text = #"Rest";
cell.detailTextLabel.text = restTime;
}
if(indexPath.row == 4){
cell.textLabel.text = #"Rating";
cell.detailTextLabel.text = [NSString stringWithFormat:#"%f",rating];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (NSDateFormatter *)dateFormatter {
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
}
return dateFormatter;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == 0){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 1){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 2){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 3){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 4){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// 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 {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
Have you debugged and checked that your navigationController isn't nil ?
I figured it out. I accidentally erased the method insertNewObject in my rootViewController. When I rewrote it, I forgot to add in ModalView * modal = [[ModalView alloc] init];. That was the problem.
Here's what the method looks like now that it's working:
- (void)insertNewObject {
ModalView * modal = [[ModalView alloc] init];
UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:modal];
[self presentModalViewController:controller animated:YES];
}