so this is basically like a slot machine type thing, very basic, but the problem Im having is that when you click the spin button the movement of the components is not animated, even though i have sent the animated argument a YES BOOL. I have no idea what I am doing wrong, any help would be appreciated.
Nick
ps download the entire project here: http://files.me.com/knyck2/dcca9y
//
// CustomPickerViewController.m
// Pickers
//
// Created by Nicholas Iannone on 1/29/10.
// Copyright 2010 Apple Inc. All rights reserved.
//
#import "CustomPickerViewController.h"
#implementation CustomPickerViewController
#synthesize column1, column2, column3, column4, column5, picker, winLabel;
-(IBAction) spin : (id) sender {
NSLog(#"even got here");
BOOL win = NO;
int numInRow = 1;
int lastVal = -1;
for (int i = 0; 1 < 5; i++) {
int newValue = random() % [self.column1 count];
if (newValue == lastVal) {
NSLog(#"even got here");
numInRow++;
}
else
numInRow = 1;
lastVal = newValue;
[picker selectRow:newValue inComponent:i animated:YES];
[picker reloadComponent:i];
if (numInRow >= 3)
win = YES;
NSLog(#"even got here");
}
if (win)
winLabel.text = #"winner!";
else {
winLabel.text = #"";
NSLog(#"even got here");
}
}
/*
// 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
}
return self;
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
UIImage *seven = [UIImage imageNamed:#"seven.png"];
UIImage *bar = [UIImage imageNamed:#"bar.png"];
UIImage *crown = [UIImage imageNamed:#"crown.png"];
UIImage *cherry = [UIImage imageNamed:#"cherry.png"];
UIImage *lemon = [UIImage imageNamed:#"lemon.png"];
UIImage *apple = [UIImage imageNamed:#"apple.png"];
for (int i = 1; i <= 5 ; i++) {
UIImageView *sevenView = [[UIImageView alloc] initWithImage: seven];
UIImageView *barView = [[UIImageView alloc] initWithImage: bar];
UIImageView *crownView = [[UIImageView alloc] initWithImage: crown];
UIImageView *cherryView = [[UIImageView alloc] initWithImage: cherry];
UIImageView *lemonView = [[UIImageView alloc] initWithImage: lemon];
UIImageView *appleView = [[UIImageView alloc] initWithImage: apple];
NSArray *imageViewArray = [[NSArray alloc] initWithObjects: sevenView, barView, crownView, cherryView, lemonView, appleView, nil];
NSString *fieldName =[[NSString alloc] initWithFormat:#"column%d", i];
[self setValue:imageViewArray forKey:fieldName];
[fieldName release];
[imageViewArray release];
[sevenView release];
[crownView release];
[barView release];
[cherryView release];
[lemonView release];
[appleView release];
}
srandom(time(NULL));
[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 {
[picker release];
[winLabel release];
[column1 release];
[column2 release];
[column3 release];
[column4 release];
[column5 release];
[super dealloc];
}
#pragma mark -
#pragma mark Picker Data Source Methods
-(NSInteger) numberOfComponentsInPickerView: (UIPickerView *) pickerView {
return 5;
}
-(NSInteger) pickerView: (UIPickerView *) pickerView numberOfRowsInComponent: (NSInteger) component {
return [self.column1 count];
}
#pragma mark Picker Delegate Methods
-(UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent: (NSInteger) component reusingView : (UIView *)view {
NSString *arrayName = [[NSString alloc] initWithFormat:#"column%d", component + 1];
NSArray *array = [self valueForKey:arrayName];
NSLog(#"got here yo");
return [array objectAtIndex: row];
NSLog(#"holyshit");
}
#end
I went back and compared my code to the book that this project is listed in and I noticed that my code would perform as expected (with animation) if I were to build into a 3.1.2 sdk and iphone sim. So something in the new xcode is skanking the animation, at least that is the way it appears.
It's probably not animating because you do [picker reloadComponent:i] right after selecting a row with animation. Reloading probably causes any animation to stop, and shouldn't be necessary since you're not actually changing the contents of the picker.
Related
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];
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)
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
Have a singleton class for BNRItemStore, but when I tried to call it, I get the above error which causes an ARC issue. Have commented out the error.
DetailViewController.m
#import "DetailViewController.h"
#import "BNRItem.h"
#import "BNRImageStore.h"
#import "BNRItemStore.h"
#implementation DetailViewController
#synthesize item;
-(id)initForNewItem:(BOOL)isNew
{
self = [super initWithNibName:#"DetailViewController" bundle:nil];
if(self){
if (isNew) {
UIBarButtonItem *doneItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:#selector(save:)];
[[self navigationItem] setRightBarButtonItem:doneItem];
UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self
action:#selector(cancel:)];
[[self navigationItem] setLeftBarButtonItem:cancelItem];
}
}
return self;
}
-(id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
#throw [NSException exceptionWithName:#"Wrong initializer"
reason:#"Use initForNewItem:"
userInfo:nil];
return nil;
}
-(void)viewDidLoad
{
[super viewDidLoad];
UIColor *clr = nil;
if ([[UIDevice currentDevice]userInterfaceIdiom]== UIUserInterfaceIdiomPad) {
clr = [UIColor colorWithRed:0.875 green:0.88 blue:0.91 alpha:1];
} else {
clr = [UIColor groupTableViewBackgroundColor];
}
[[self view]setBackgroundColor:clr];
}
- (void)viewDidUnload {
nameField = nil;
serialNumberField = nil;
valueField = nil;
dateLabel = nil;
imageView = nil;
[super viewDidUnload];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[nameField setText:[item itemName]];
[serialNumberField setText:[item serialNumber]];
[valueField setText:[NSString stringWithFormat:#"%d", [item valueInDollars]]];
// Create a NSDateFormatter that will turn a date into a simple date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
// Use filtered NSDate object to set dateLabel contents
[dateLabel setText:[dateFormatter stringFromDate:[item dateCreated]]];
NSString *imageKey = [item imageKey];
if (imageKey) {
// Get image for image key from image store
UIImage *imageToDisplay = [[BNRImageStore sharedStore]imageForKey:imageKey];
// Use that image to put on the screen in imageview
[imageView setImage:imageToDisplay];
} else {
// Clear the imageview
[imageView setImage:nil];
}
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// Clear first responder
[[self view]endEditing:YES];
// "Save" changes to item
[item setItemName:[nameField text]];
[item setSerialNumber:[serialNumberField text]];
[item setValueInDollars:[[valueField text] intValue]];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)io
{
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
return YES;
} else {
return (io==UIInterfaceOrientationPortrait);
}
}
-(void)setItem:(BNRItem *)i
{
item = i;
[[self navigationItem] setTitle:[item itemName]];
}
- (IBAction)takePicture:(id)sender {
if ([imagePickerPopover isPopoverVisible]) {
// If the popover is already up, get rid of it
[imagePickerPopover dismissPopoverAnimated:YES];
imagePickerPopover = nil;
return;
}
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc]init];
// If our device has a camera, we want to take a picture, otherwise, we
// just pick from the photo library
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
} else {
[imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
// This line of code will generate a warning right now, ignore it
[imagePicker setDelegate:self];
//Place image picker on the screen
// Check for iPad device before instantiating the popover controller
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
// Create a new popover controller that will display the imagepicker
imagePickerPopover = [[UIPopoverController alloc]initWithContentViewController:imagePicker];
[imagePickerPopover setDelegate:self];
// Display the popover controller; sender
// is the camera bar button item
[imagePickerPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
} else {
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
}
-(void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
NSLog(#"User dismissed popover");
imagePickerPopover = nil;
}
- (IBAction)backgroundTapped:(id)sender {
[[self view]endEditing:YES];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *oldKey = [item imageKey];
// Did the item already have an image?
if (oldKey) {
// Delete the old image
[[BNRImageStore sharedStore]deleteImageForKey:oldKey];
}
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// Create a CFUUID object - it knows how to create unique identifier strings
CFUUIDRef newUniqueID = CFUUIDCreate(kCFAllocatorDefault);
// Create a string from unique identifier
CFStringRef newUniqueIDString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueID); // Incompatible integer to pointer conversion initializing
// Use that unique ID to set our item's imageKey
NSString *key = (__bridge NSString *)newUniqueIDString;
[item setImageKey:key];
// Store image in the BNRImageStore with this key
[[BNRImageStore sharedStore] setImage:image forKey:[item imageKey]];
CFRelease(newUniqueIDString);
CFRelease(newUniqueID);
[imageView setImage:image];
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
// If on the phone, the image picker is presented modally. Dismiss it.
[self dismissViewControllerAnimated:YES completion:nil];
} else {
// If on the pad, the image picker is in the popover. Dismiss the popover.
[imagePickerPopover dismissPopoverAnimated:YES];
imagePickerPopover = nil;
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
-(void)save:(id)sender
{
[[self presentingViewController]dismissViewControllerAnimated:YES
completion:nil];
}
-(void)cancel:(id)sender
{
// If the user cancelled, then remove the BNRItem from the store
[[BNRItemStore sharedStore]removeItem:item]; // No known class method for selector 'sharedStore'
[[self presentingViewController]dismissViewControllerAnimated:YES completion:nil];
}
DetailViewController.h
#import <UIKit/UIKit.h>
#class BNRItem;
#interface DetailViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate,UITextFieldDelegate, UIPopoverControllerDelegate>
{
__weak IBOutlet UITextField *nameField;
__weak IBOutlet UITextField *serialNumberField;
__weak IBOutlet UITextField *valueField;
__weak IBOutlet UILabel *dateLabel;
__weak IBOutlet UIImageView *imageView;
UIPopoverController *imagePickerPopover;
}
#property(nonatomic,strong)BNRItem *item;
-(id)initForNewItem:(BOOL)isNew;
- (IBAction)takePicture:(id)sender;
- (IBAction)backgroundTapped:(id)sender;
#end
BNRItemStore.m
#import "BNRItemStore.h"
#import "BNRItem.h"
#implementation BNRItemStore
+ (BNRItemStore *)defaultStore
{
static BNRItemStore *defaultStore = nil;
if(!defaultStore)
defaultStore = [[super allocWithZone:nil] init];
return defaultStore;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self defaultStore];
}
- (id)init
{
self = [super init];
if(self) {
allItems = [[NSMutableArray alloc] init];
}
return self;
}
- (void)removeItem:(BNRItem *)p
{
[allItems removeObjectIdenticalTo:p];
}
- (NSArray *)allItems
{
return allItems;
}
- (void)moveItemAtIndex:(int)from
toIndex:(int)to
{
if (from == to) {
return;
}
// Get pointer to object being moved so we can re-insert it
BNRItem *p = [allItems objectAtIndex:from];
// Remove p from array
[allItems removeObjectAtIndex:from];
// Insert p in array at new location
[allItems insertObject:p atIndex:to];
}
- (BNRItem *)createItem
{
BNRItem *p = [BNRItem randomItem];
[allItems addObject:p];
return p;
}
#end
BNRItemStore.h
#import <Foundation/Foundation.h>
#class BNRItem;
#interface BNRItemStore : NSObject
{
NSMutableArray *allItems;
}
+ (BNRItemStore *)defaultStore;
- (void)removeItem:(BNRItem *)p;
- (NSArray *)allItems;
- (BNRItem *)createItem;
- (void)moveItemAtIndex:(int)from
toIndex:(int)to;
#end
You are calling +sharedStore on BNRItemStore where your error occurs. This is because it really does not exist according to the code you posted.
All of the others calling +sharedStore are using the one presumably made available by BNRImageStore which you didn't provide. I assume it exists in that class? :)
In short, change:
[[BNRItemStore sharedStore]removeItem:item];
to
[[BNRImageStore sharedStore]removeItem:item];
Once again working through beginning iphone development and I am putting together a bunch of UIPicker type apps, the last one of which is a slot machine type of game, super simple. Anyway I am not really understanding why this error is coming up. to my understanding the picker view is asking its delegate for an object in the array that is past the range available to that array.
That being said I have no idea why it is doing this or how to fix it, any help would be appreciated, heres the code from the particular .m file( get the full project here: http://files.me.com/knyck2/89q3w3 ):
//
// CustomPickerViewController.m
// Pickers
//
// Created by Nicholas Iannone on 1/29/10.
// Copyright 2010 Apple Inc. All rights reserved.
//
#import "CustomPickerViewController.h"
#implementation CustomPickerViewController
#synthesize column1, column2, column3, column4, column5, picker, winLabel;
-(IBAction) spin : (id) sender {
NSLog(#"even got here");
BOOL win = NO;
int numInRow = 1;
int lastVal = -1;
for (int i = 0; 1 < 5; i++) {
int newValue = random() % [self.column1 count];
if (newValue == lastVal) {
NSLog(#"even got here");
numInRow++;
}
else
numInRow = 1;
lastVal = newValue;
[picker selectRow:newValue inComponent:i animated:YES];
[picker reloadComponent:i];
if (numInRow >= 3)
win = YES;
NSLog(#"even got here");
}
if (win)
winLabel.text = #"winner!";
else {
winLabel.text = #"";
NSLog(#"even got here");
}
}
/*
// 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
}
return self;
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
UIImage *seven = [UIImage imageNamed:#"seven.png"];
UIImage *bar = [UIImage imageNamed:#"bar.png"];
UIImage *crown = [UIImage imageNamed:#"crown.png"];
UIImage *cherry = [UIImage imageNamed:#"cherry.png"];
UIImage *lemon = [UIImage imageNamed:#"lemon.png"];
UIImage *apple = [UIImage imageNamed:#"apple.png"];
for (int i = 1; i <= 5 ; i++) {
UIImageView *sevenView = [[UIImageView alloc] initWithImage: seven];
UIImageView *barView = [[UIImageView alloc] initWithImage: bar];
UIImageView *crownView = [[UIImageView alloc] initWithImage: crown];
UIImageView *cherryView = [[UIImageView alloc] initWithImage: cherry];
UIImageView *lemonView = [[UIImageView alloc] initWithImage: lemon];
UIImageView *appleView = [[UIImageView alloc] initWithImage: apple];
NSArray *imageViewArray = [[NSArray alloc] initWithObjects: sevenView, barView, crownView, cherryView, lemonView, appleView, nil];
NSString *fieldName =[[NSString alloc] initWithFormat:#"column%d", i];
[self setValue:imageViewArray forKey:fieldName];
[fieldName release];
[imageViewArray release];
[sevenView release];
[crownView release];
[barView release];
[cherryView release];
[lemonView release];
[appleView release];
}
srandom(time(NULL));
[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 {
[picker release];
[winLabel release];
[column1 release];
[column2 release];
[column3 release];
[column4 release];
[column5 release];
[super dealloc];
}
#pragma mark -
#pragma mark Picker Data Source Methods
-(NSInteger) numberOfComponentsInPickerView: (UIPickerView *) pickerView {
return 5;
}
-(NSInteger) pickerView: (UIPickerView *) pickerView numberOfRowsInComponent: (NSInteger) component {
return [self.column1 count];
}
#pragma mark Picker Delegate Methods
-(UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent: (NSInteger) component reusingView : (UIView *)view {
NSString *arrayName = [[NSString alloc] initWithFormat:#"column%d", component + 1];
NSArray *array = [self valueForKey:arrayName];
NSLog(#"got here yo");
return [array objectAtIndex: row];
NSLog(#"holyshit");
}
#end
The reason why it's breaking is this loop. Take a look at your for loop condition:
1 < 5. Yes, 1 is always less than 5. This means that you have an infinite loop. I'm sure you meant i < 5.
for (int i = 0; 1 < 5; i++) {
int newValue = random() % [self.column1 count];
if (newValue == lastVal) {
NSLog(#"even got here");
numInRow++;
}
else
numInRow = 1;
lastVal = newValue;
[picker selectRow:newValue inComponent:i animated:YES];
[picker reloadComponent:i];
if (numInRow >= 3)
win = YES;
NSLog(#"even got here");
}
You're testing if 1 < 5, which is always true. You want i < 5.