Button action with Segue and Alertview - xcode4

I have UIStoryboardSegue setup and want to perform an AlertView if a certain condition exists, cancel the alert to stop performSegue and OK to carry on with performSegue. Only problem I have is dealing with the sender id, since the performSeguewithIdentifier needs to go in the alertView button click method. How do I keep the sender(id)?
- (IBAction)drink1Button:(id)sender {
if([drink1Units.text intValue] > 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"You Chose" message:#"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"DrinkSegue"]) {
// Get destination view
DrinksListViewController *selectedDrink = [segue destinationViewController];
// Get button tag
NSInteger tagIndex = [(UIButton *)sender tag];
// Set the selected button in the new view
[selectedDrink setSelectedButton:tagIndex];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
[self performSegueWithIdentifier:#"DrinkSegue" sender:sender];
}

Related

How to fix UISearchBar returning NSRangeException when clear button is clicked? (FIXED!!!)

I have implemented a UISearchBar in my app that is crashing when I hit the clear button and while there's one item found. It's like I type in some character, the app searches and display 1 item, but I when I clear the search, it crashes.
I searched stackoverflow and I am aware that the problem is with the array that holds the search items cause when I hit the clear button the array becomes empty and the tableview index path.row can't be displayed.
Also, if the search returns no item and I hit the clear button I get a similar error message buy this time saying the I got an empty array.
The app stops here:
NSDictionary *itemAtIndice =(NSDictionary *)[filteredCodigos objectAtIndex:indexPath.row];
The problem is that I simple don't know what to do!!!
Here is the error:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
And here is my code::
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length == 0) {
isFiltered = NO;
} else {
isFiltered = YES;
filteredCodigos = [[NSMutableArray alloc]init];
for (NSDictionary *item in values) {
NSString *string = [item objectForKey:#"NAME"];
NSRange stringRange = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound) {
[filteredCodigos addObject:item];
}
}
}
[self.tableView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[self.Pesquisa resignFirstResponder];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFiltered) {
return [filteredCodigos count];
}
return values.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSDictionary *itemAtIndex =(NSDictionary *)[values objectAtIndex:indexPath.row];
NSDictionary *itemAtIndice =(NSDictionary *)[filteredCodigos objectAtIndex:indexPath.row];
if (!isFiltered) {
cell.textLabel.text = [itemAtIndex objectForKey:#"SYMBOL"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
cell.detailTextLabel.text = [itemAtIndex objectForKey:#"NAME"];
} else {
cell.textLabel.text = [itemAtIndice objectForKey:#"SYMBOL"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
cell.detailTextLabel.text = [itemAtIndice objectForKey:#"NAME"];
}
return cell;
}
filteredCodigos is declared outside of searchBar:textDidChange: and is used in multiple places but is assigned to in searchBar:textDidChange:. Most likely, some other code is trying to access members of filteredCodigos which is unassigned or empty. Enabling exception breakpoints will help you track it down.
As a side note. You might look at NSPredicate to filter your items instead of the for loop.
Finally managed to fix this issue.
I just replaced indexPath.row for lastObject at the line that was giving me the error:
So, before:
NSDictionary *itemAtIndice =(NSDictionary *)[filteredCodigos objectAtIndex:indexPath.row];
And after:
NSDictionary *itemAtIndice =(NSDictionary *)[filteredCodigos lastObject];

segue from searchResultsTableView

I currently have a searchdisplaycontroller set up and working. The original table view has a segue set up for the title and image to be passed to a detail view. I would like this segue to happen from the search display controller but this is not happening? I know this is possible but can't seem to get it to work? My code is:
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.detailViewController setDetailItem:[[contentsList objectAtIndex:indexPath.section]
objectAtIndex: indexPath.row]];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detailview"]) {
self.detailViewController=segue.destinationViewController;
}
}
#end
and in the detail view to set it all up:
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.navigationItem.title = [self.detailItem objectForKey:#"name"];
[self.detailImage setImage:[UIImage imageNamed:self.detailItem[#"image"]]];
}
}
I would be very grateful for any help in solving this issue :)
You can Segue from a Search Display Controller by calling performSegueWithIdentifier:sender: from tableView:didSelectRowAtIndexPath: like this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Get the UITableViewCell that was selected
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
// Then this will call prepareForSegue:sender: with selectedCell as sender
[self performSegueWithIdentifier:#"detailview" sender:selectedCell];
}
Then on prepareForSegue:sender: you set your destinationViewController properties
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detailview"]) {
// Set your destinationViewController properties here
}
}

AVAudioPlayer Notification issue

So I'm almost done with my app and I've hit a wall and cannot get around this final problem.
I basically have 2 view's. A main page and the game play screen.
On the first play the game works fine, but when i leave the main screen and then return to the game screen all the sounds are duplicating and firing the the playerItemDidReachEnd early (because I'm guessing there are 2 instances of it, but it cannot seem to get the player to stop this. Here is the basic code causing this. Any help would go a long way, thanks. I'm not sure if my issue is i'm creating multiple instances of View2 in View1 or if I'm creating multiple player objects in view2 thus duplicating the notification.
I know there is a lot going on in my - (void)playerItemDidReachEnd:(NSNotification *)notification, but it works fine on the first load of the page, its only when I click "go back to view1" and then go back in to View2 that the issue happens.
View1ViewController.h
----------------------
#import "(i know here are arrows here, but can't make them show)UIKit/UIKit.h>
#import "ApplicationViewController.h"
#interface MonsterSpellViewController : UIViewController {
}
-(IBAction)showView1;
View2ViewController.m
----------------------
-(IBAction)showView2{
ApplicationViewController *view2 = [[ApplicationViewController alloc]initWithNibName:#"ApplicationViewController" bundle:nil];
view2.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:view2 animated:YES];
}
View2ViewController.h
------------------------
#import "(i know here are arrows here, but can't make them show)UIKit/UIKit.h>
#import "(i know here are arrows here, but can't make them show)AVFoundation/AVFoundation.h>
#class AVAudioPlayer;
#interface ApplicationViewController : UIViewController{
AVAudioPlayer *avPlayer;
}
View2ViewController.m
-------------------------
#import "View2ViewController.h"
#synthesize avPlayer;
-(AVAudioPlayer *)avPlayer {
if(!avPlayer) avPlayer = [[AVAudioPlayer alloc]init];
return avPlayer;
}
-(void) viewDidLoad
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:avPlayer];
}
-(IBAction)playSoundTest
{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/monster3.mp3", [[NSBundle mainBundle] resourcePath]]];
self.avPlayer = [AVPlayer playerWithURL:url];
[self.avPlayer play];
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
//[player seekToTime:kCMTimeZero];
if (playEscape == YES) {
[self btnEscapeSound];
playEscape = NO;
}
if ((startButton.hidden == NO) && (letterCount != -1) && (playFinal == YES))
{
[self btnFinalSound];
playFinal = NO;
playEscape = YES;
}
NSLog(#"Player Check accessed");
if (letterCount == 3) {
if (Winner == letterCount) {
//moveNextSound = YES;
if (intLoopCount < 104)
{
if (intLoopCount<104) {
[self btnStartOver:intLoopCount];
playFinal = NO;
//intLoopCount++;
}
if (intLoopCount==104) {
startButton.hidden=NO;
playFinal = YES;
}
}
}
}
if (letterCount == 4) {
if (Winner == letterCount) {
//moveNextSound = YES;
if (intLoopCount < 105)
{
[self btnStartOver:intLoopCount];
//intLoopCount++;
if (intLoopCount==105) {
startButton.hidden=NO;
playFinal = YES;
}
}
}
}
}
}
-(IBAction)goBack:(id)sender{
[self dismissModalViewControllerAnimated:YES];
}
Try adding [view2 release]; after [self presentModalViewController:view2 animated:YES];

Help with UITableView / Navigation Setup with UITabBar Interface

I'm trying to set up a Tab Bar Application as my root controller, and one of the tabs to be a Navigation setup. On my Root View Controller of the Navigation View, I have one child level that is a subclass of the UIViewController called IntervalViewController.
I have this in my Root View Controller (IntervalSetupViewController.m):
#import "IntervalSetupViewController.h"
#import "IntervalViewController.h"
#implementation IntervalSetupViewController
#synthesize controllers; // My Array for the Table View Cells
- (void)viewDidLoad {
self.title = #"Interval Setup";
NSMutableArray *array = [[NSMutableArray alloc] init];
// Interval List Setup
IntervalViewController *newInterval = [[IntervalViewController alloc]
initWithStyle:UITableViewStylePlain];
newInterval.title = #"Interval 1";
[array addObject:newInterval];
[newInterval release];
self.controllers = array;
[array release];
[super viewDidLoad];
}
- (void)viewDidUnload {
self.controllers = nil;
[super viewDidUnload];
}
- (void)dealloc {
[controllers release];
[super dealloc];
}
#pragma mark -
#pragma mark Table Data Source Methods
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
return [self.controllers count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *IntervalCell = #"IntervalCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IntervalCell];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:IntervalCell] autorelease];
}
// Configure the cell
NSUInteger row = [indexPath row];
IntervalViewController *newController = [controllers objectAtIndex:row];
cell.textLabel.text = newController.title;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark Table View Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
IntervalViewController *nextController = [self.controllers objectAtIndex:row];
[self.navigationController pushViewController:nextController animated:YES];
}
#end
This is the error screen from the console:
* -[IntervalViewController initWithStyle:]: unrecognized selector sent to instance 0x3b33e60
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[IntervalViewController initWithStyle:]: unrecognized selector sent to instance 0x3b33e60'
I assume that I am passing an invalid argument to my initWithStyle method, but I thought UITableViewStylePlain was a valid parameter. Am I setting this up right? I was following the example in APress Beginning iPhone Development 3 book and trying to modify it a little to what I wanted to do, but I'm new to coding. Thanks!
initWithStyle is used to initialize a UITableViewController not a UIViewController

How to load UIImagePickerController at viewLoad

This seems like a really simple idea... I have a button that says "load a picture". When that button is clicked I want to remove the current view, load a new one, open the image picker, get the selected picture, and display it in the view that I just loaded. I have read several documents that say UIImagePicker does not work in viewDidLoad, and found one thread that suggested using awakeFromNib instead but even that does not work... here is code. Please help.
In MenuViewController
-(IBAction)loadPictureButtonPressed
{
UIView *parent = [self.view superview];
if(self.loadPictureViewController.view.superview == nil)
{
if(self.loadPictureViewController == nil)
{
LoadPictureViewController *picController = [[LoadPictureViewController alloc]
initWithNibName:#"LoadPictureView" bundle: nil];
self.loadPictureViewController = picController;
[picController release];
}
}
[parent addSubview:self.loadPictureViewController.view];
[self.view removeFromSuperview];
}
In LoadPictureViewController
-(void)awakeFromNib
{
if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
[picker release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error!"
message:#"Device does not support photo library";
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Again I have tried placing this code in both viewDidLoad and awakeFromNib. Please help
I simply set an NSTimer in viewDidLoad with a timer of 0 to select the method where I load it.
[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:#selector(camera) userInfo:nil repeats:NO];
Instead of NSTimer, you probably want to use the following in -viewDidLoad,
[self performSelector:#selector(camera) withObject:nil afterDelay:0];

Resources