Saving buttonIndex into object(NSNumber) - iphone

I am trying to save the selectedIndex of actionsheet into an object. But why does it always read 0?
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSNumber *type, *count;
if ([actionSheet.title isEqualToString:#"Select Taxi Type"]) {
if (buttonIndex !=3) {
type = [NSNumber numberWithInteger:buttonIndex];
UIActionSheet *taxiCountQuery = [[UIActionSheet alloc] initWithTitle:#"Select Taxi Count" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"1", #"2", #"3", nil];
taxiCountQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
taxiCountQuery.tag = actionSheet.tag;
[taxiCountQuery showFromTabBar:self.tabBarController.tabBar];
[taxiCountQuery release];
}
}
else if ([actionSheet.title isEqualToString:#"Select Taxi Count"]){
if (buttonIndex !=3) {
NSLog(#"buttonIndex:%i", buttonIndex);
count = [NSNumber numberWithInteger:buttonIndex];
NSLog(#"type:%f", type); // always read 0
NSLog(#"count:%f", count); // always read 0
}
}
}
EDIT - 2nd part
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSNumber *type = [[NSNumber alloc] init];
if ([actionSheet.title isEqualToString:#"Select Taxi Type"]) {
if (buttonIndex !=3) {
type = [NSNumber numberWithInteger:buttonIndex];
UIActionSheet *taxiCountQuery = [[UIActionSheet alloc] initWithTitle:#"Select Taxi Count" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"1", #"2", #"3", nil];
taxiCountQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
taxiCountQuery.tag = actionSheet.tag;
[taxiCountQuery showFromTabBar:self.tabBarController.tabBar];
[taxiCountQuery release];
}
}
else if ([actionSheet.title isEqualToString:#"Select Taxi Count"]){
if (buttonIndex !=3) {
NSNumber *count = [[NSNumber alloc] initWithInteger:buttonIndex+1];
NSLog(#"buttonIndex:%i", buttonIndex);
count = [NSNumber numberWithInteger:buttonIndex +1];
NSLog(#"type:%i", [type intValue]); // always read 0
NSLog(#"count:%i", [count intValue]); // reads fine now
[count release];
}
}
}

NSNumber is an object that can hold basic types for storing in data structures like NSDictionary and NSArray. The %f in the NSLog is looking for a double.
This code should be giving you a warning.
If you do NSLog(#"%i",[type intValue]) you will get the right answer.

Please check out this code.
NSNumber *numberNs = [[NSNumber alloc] initWithInteger:buttonIndex];
Hope this helps you.

Related

How to display NSArray objects in the buttons of a UIActionSheet

I'm trying to populate a UIActionSheet button list with the result from an NSArray. I have cityTitleNodeArray which is an NSArray (nslog output below). At the moment it only displays the first item in the NSArray as the first button in the UIActionSheet
I would like it to look like this (except the array info should all come from cityTitleNodeArray) :
NSArray *array = [[NSArray alloc] initWithObjects: cityTitleNodeArray, #"city2", #"city3", #"city4", #"city5", #"city6", #"city7", #"city8",#"city9", #"city10", #"city11", #"city12", #"city13", #"city14", #"city15", #"city16", nil];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Title Here"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
for (NSString *title in array) {
[actionSheet addButtonWithTitle:title];
}
[actionSheet addButtonWithTitle:#"Cancel"];
actionSheet.cancelButtonIndex = [array count];
[actionSheet showInView:self.view];
-(void)requestCityData {
NSError *requestError = nil;
NSString *savedValue = [[NSUserDefaults standardUserDefaults] stringForKey:#"token"];
NSString *stringWithToken = [NSString stringWithFormat:#"%#&token=%#",kCityURL, savedValue];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringWithToken]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&requestError];
NSError *jsonParsingError = nil;
if (requestError) {
NSLog(#"sync. request failed with error: %#", requestError);
}
else {
// handle data
NSDictionary *publicData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
publicCityDataArray = [publicData objectForKey:#"data"];
for (NSDictionary *publicCityDataDict in publicCityDataArray) {
cityTitleNodeArray = [publicCityDataDict objectForKey:#"name"];
NSLog(#"cityTitleNodeArray from requestCityData output is %#",cityTitleNodeArray);
}
}
}
the cityTitleNodeArray output is:
`cityTitleNodeArray` from `requestCityData` output is Roma
2013-09-16 12:49:28.001 1000 [3980:907] cityTitleNodeArray from requestCityData output is Milano
2013-09-16 12:49:28.002 1000 [3980:907] cityTitleNodeArray from requestCityData output is Rimini
2013-09-16 12:49:28.002 1000 [3980:907] cityTitleNodeArray from requestCityData output is Venezia
2013-09-16 12:49:28.003 1000 [3980:907] cityTitleNodeArray from requestCityData output is Firenze
2013-09-16 12:49:28.003 1000 [3980:907] cityTitleNodeArray from requestCityData output is Napoli
NSArray *array = [[NSArray alloc] initWithObjects:
#"1st Button",
#"2nd Button",
#"3rd Button",
#"4th Button",
nil];
UIActionSheet* actionSheet = [[UIActionSheet alloc] init];
actionSheet.title = #"Cities Name";
actionSheet.delegate = self;
for(int i=0;i<[array count];i++)
{
[actionSheet addButtonWithTitle:[array objectAtIndex:i]];
}
actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:#"Cancel"];
[actionSheet showInView:[UIApplication sharedApplication].keyWindow];
For Setting Title of Buttons From the array
UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:#"Title" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:[array objectAtIndex:0],[array objectAtIndex:1],[array objectAtIndex:2], nil];
[actionSheet showInView:self.view];
In the delegate Method
pragma mark Action Sheet Delegate method
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
switch (buttonIndex) {
case 0:
{
//Actions on pressing Button 1
}
break;
case 1:
{
//Actions on pressing Button 2
}
break;
case 2:
{
//Actions on pressing Button 3
}
break;
default:
break;
}
}
Try this
NSArray *array = [[NSArray alloc] initWithObjects:
[NSString stringWithString:#"1st Button"],
[NSString stringWithString:#"2nd Button"],
[NSString stringWithString:#"3rd Button"],
[NSString stringWithString:#"4th Button"],
nil];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Title Here"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
// ObjC Fast Enumeration
for (NSString *title in array) {
[actionSheet addButtonWithTitle:title];
}
[actionSheet addButtonWithTitle:#"Cancel"];
actionSheet.cancelButtonIndex = [array count];
[actionSheet showInView:self.view];

Retrieving Position, Title, and Snippet for Multiple Markers Using Google Maps for iOS

The problem I'm having it that when I long touch the map it saves the data to Core Data and I can retrieve this data by NSLogs but I cannot figure out how to create multiple map markers from this data. Can anyone give me an example of a for loop for drawing these markers?
-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate{
location = coordinate;
[self alertview1];
}
- (void) alertview1 {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Save Map Location" message:#"Enter Title & Description" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
[av setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[[av textFieldAtIndex:1] setSecureTextEntry:NO];
[[av textFieldAtIndex:0] setPlaceholder:#"Title"];
[[av textFieldAtIndex:1] setPlaceholder:#"Description"];
[av show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex != alertView.cancelButtonIndex) {
markerTitle = [alertView textFieldAtIndex:0].text;
markerSnippet = [alertView textFieldAtIndex:1].text;
NSLog(#"1 %#", [alertView textFieldAtIndex:0].text);
NSLog(#"2 %#", [alertView textFieldAtIndex:1].text);
[self saveMarker];
}
- (void) saveMarker{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Marker" inManagedObjectContext:context];
[newDevice setValue:[NSNumber numberWithDouble:location.latitude] forKey:#"latitude"];
[newDevice setValue:[NSNumber numberWithDouble:location.longitude] forKey:#"longitude"];
[newDevice setValue:markerTitle forKey:#"title"];
[newDevice setValue:markerSnippet forKey:#"snippet"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
[self fetchMarkers];
}
- (void) fetchMarkers {
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Marker"];
self.markers = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSArray *title = [self.markers valueForKey:#"Title"];
NSArray *snippet = [self.markers valueForKey:#"Snippet"];
NSArray *latitude = [self.markers valueForKey:#"Latitude"];
NSArray *longitude = [self.markers valueForKey:#"Longitude"];
NSLog (#"%#", title);
NSLog (#"%#", snippet);
NSLog (#"%#", latitude);
NSLog (#"%#", longitude);
double lat = [latitude doubleValue];
double lng = [longitude doubleValue];
for (GMSMarker *marker in title) {
GMSMarker *mkr = [[GMSMarker alloc] init];
[mkr setPosition:CLLocationCoordinate2DMake(lat,lng)];
[mkr setAnimated:YES];
[mkr setTitle:title];
[mkr setSnippet:snippet];
[mkr setMap:self.mapView1];
}
}
After banging my head against the wall for hours and taking a few shots it finally came to me and was very simple. I stuck the data from core data in separate arrays and indexes the markers then indexed the arrays in a variable. Anyway here is the code. If anyone else has a better way of doing this please let me know. I am still learning Objective C and only started a couple months ago so there probably is a better solution but this at least works.
-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate{
location = coordinate;
[self alertview1];
}
- (void) alertview1 {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Save Map Location" message:#"Enter Title & Description" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
[av setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
// Alert style customization
[[av textFieldAtIndex:1] setSecureTextEntry:NO];
[[av textFieldAtIndex:0] setPlaceholder:#"Title"];
[[av textFieldAtIndex:1] setPlaceholder:#"Description"];
[av show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex != alertView.cancelButtonIndex) {
markerTitle = [alertView textFieldAtIndex:0].text;
markerSnippet = [alertView textFieldAtIndex:1].text;
NSLog(#"1 %#", [alertView textFieldAtIndex:0].text);
NSLog(#"2 %#", [alertView textFieldAtIndex:1].text);
[self saveMarker];
} else {
// this is where you would handle any actions for "Cancel"
}
}
- (void) saveMarker{
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Marker" inManagedObjectContext:context];
[newDevice setValue:[NSNumber numberWithDouble:location.latitude] forKey:#"latitude"];
[newDevice setValue:[NSNumber numberWithDouble:location.longitude] forKey:#"longitude"];
[newDevice setValue:markerTitle forKey:#"title"];
[newDevice setValue:markerSnippet forKey:#"snippet"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
[self fetchMarkers];
}
- (void) fetchMarkers {
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Marker"];
self.markers = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSMutableArray *title = [self.markers valueForKey:#"Title"];
NSMutableArray *snippet = [self.markers valueForKey:#"Snippet"];
NSMutableArray *latitude = [self.markers valueForKey:#"Latitude"];
NSMutableArray *longitude = [self.markers valueForKey:#"Longitude"];
for (int i = 0; i < [title count]; i++){
GMSMarker *mkr = [[GMSMarker alloc] init];
double lat = [[latitude objectAtIndex:i] doubleValue];
double lng = [[longitude objectAtIndex:i] doubleValue];
NSString *T = [title objectAtIndex:i];
NSString *S = [snippet objectAtIndex:i];
[mkr setPosition:CLLocationCoordinate2DMake(lat, lng)];
[mkr setAnimated:YES];
[mkr setTitle:T];
[mkr setSnippet:S];
[mkr setMap:self.mapView1];
}

Customized Annotation

i have a question regarding customized annotation here. Here is how i show the pin but i wish to insert an image in to the annotation when the user click on the pin. how can i do that?
- (void) showMarkingOnMap:(Service *) ser
{
if (!self.mapView.loaded) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iPoly"
message:#"Failed to load the map."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
return;
}
id<AGSLayerView> graphicsLayerView = [self.mapView.mapLayerViews objectForKey:#"GraphicsLayer"];
AGSGraphicsLayer *graphicsLayer = (AGSGraphicsLayer*)graphicsLayerView.agsLayer;
[graphicsLayer removeAllGraphics];
// Create a symbols png graphic
AGSPictureMarkerSymbol *genSymbol = [AGSPictureMarkerSymbol pictureMarkerSymbolWithImageNamed:#"pushpin.png"];
ServiceInfoTemplate *infoTemplate = [[ServiceInfoTemplate alloc] init];
AGSGraphic *genGraphic;
AGSPoint *genPt;
NSMutableDictionary *dic= [[NSMutableDictionary alloc] init];
[dic setObject:[ser name] forKey:#"NAME"];
if([ser.location isEqualToString: #"\n"] || (ser.location == nil)){
[dic setObject:#"" forKey:#"DESC"];
} else {
[dic setObject:[ser location] forKey:#"DESC"];
}
genPt = [AGSPoint pointWithX:[[ser xcoordinate] floatValue]
y:[[ser ycoordinate] floatValue]
spatialReference:self.mapView.spatialReference];
genGraphic = [[AGSGraphic alloc] initWithGeometry:genPt symbol:genSymbol attributes:dic infoTemplateDelegate:infoTemplate];
[graphicsLayer addGraphic:genGraphic];
[graphicsLayer dataChanged];
[self.mapView zoomWithFactor:0.1 atAnchorPoint:genPt.cgPoint animated:NO];
[self.mapView centerAtPoint:genPt animated:YES];
//CGPoint *pt = CGPointMake([[ser ycoordinate] floatValue], [[ser xcoordinate] floatValue]);
}
It's not as easy as you might hope/think. Here's a full tutorial on how to do it.
Note that with this implementation, your callout will occupy the entire width of the view.
See:
http://blog.asolutions.com/2010/09/building-custom-map-annotation-callouts-part-1/

UIAlertView pops up twice?

I am trying to use two UIAlertViews but both pop up when i trigger one.
-(IBAction)continueGame_button:(id)sender {
//=====CHECK IF THERE IS AN ON-GOING GAME, IF SO CONTINUE=====//
AccessCurrentGameData *isThereAnOngoingGameFunction = [AccessCurrentGameData new];
BOOL ongoingGame = [isThereAnOngoingGameFunction checkIfGameOngoing];
[isThereAnOngoingGameFunction release];
NSLog(#"+ + +continueGame_button+ + +");
NSLog(#"ongoingGame = %#\n", (ongoingGame ? #"YES" : #"NO"));
if (ongoingGame == YES) {
NSLog(#"+++++++++ ONGOING GAME +++++++++");
myAlert = [[UIAlertView alloc] initWithTitle:#"Fortsätta spel"
message:#"Det finns ett aktivt spel, klicka Spela eller Tillbaka"
delegate:self
cancelButtonTitle:#"Tillbaka"
otherButtonTitles:#"Spela", nil];
myAlert.tag=kTagContinueGame;
[myAlert show];
[myAlert release];
}
}
-(IBAction)newGame_button:(id)sender {
myAlert = [[UIAlertView alloc] initWithTitle:#"Varning"
message:#"Om du går vidare kommer pågående spel stoppas och nollställas!"
delegate:self
cancelButtonTitle:#"Tillbaka"
otherButtonTitles:#"Fortsätt", nil];
myAlert.tag=kTagNewGame;
[myAlert show];
myAlert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
switch(myAlert.tag ) {
case kTagContinueGame:
NSLog(#"kTagContinueGame");
break;
case kTagNewGame:
NSLog(#"kTagNewGame");
AccessCurrentGameData *zeroCurrentGameFileFunction = [AccessCurrentGameData new];
[zeroCurrentGameFileFunction firstCreationOrRestoreOfGameDataFile];
[zeroCurrentGameFileFunction release];
NewGameViewController * temp = [[NewGameViewController alloc] init];
[self setNewGameViewController:temp];
[temp release];
[[self navigationController] pushViewController:newGameViewController animated:YES];
break;
default:
break;
}
}
Check your IBOutlet. You may have 1 button that is connected to 2 of your IBAction's.
If it's a UIButton, check the touchUpInside.

UIAlert View-for yes/no condition

my app needs alert msg and if yes button pressed then one more alert msg and then i have to called a method.This is my code:
-(IBAction)resetPressed:(id)sender
{
NSString *title= [NSString stringWithFormat:#"Warning"];
NSString *message = [NSString stringWithFormat:#"Are you sure you want to Reset"];
NSString *ok = [NSString stringWithFormat:#"No"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (alertView.tag ==1)
{
NSString *title= [NSString stringWithFormat:#"Warning"];
NSString *message = [NSString stringWithFormat:#"Are you sure you want to Reset"];
NSString *ok = [NSString stringWithFormat:#"No"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
alert.tag =2;
[alert show];
[alert release];
}
else if(alertView.tag ==2)
{
[self resetArray];
}
}
Thanks.
I'm not sure what your goal is but a few things look wrong to me anyways:
First of all you should create your strings this way:
NSString *title= #"Warning";
There's no need to use stringWithFormat in your case.
Then, it doesn't seem you properly set the first UIAlert's tag to 1, and the default value for tags is 0 so I guess the if statements in didDismissWithButtonIndex are never true.
Also, you should check which button was pressed using buttonIndex, otherwise you are going to show both alert and call [self resetArray] whichever button is pressed by the user.
Hope that helps.
In your code, you create the first alert, but never actually set the tag on it. You should do:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
alert.tag = 1; //Or 2, or something.
[alert show];
[alert release];
Then the code in your delegate method will run.
Please define two separate UIAlertView in .h file
#interface XYZViewController:UIViewController
{
UIAlertView *firstAlertView;
UIAlertView *secondAlertView;
}
Now in your .m file modify as below:
-(IBAction)resetPressed:(id)sender
{
NSString *title= [NSString stringWithFormat:#"Warning"];
NSString *message = [NSString stringWithFormat:#"Are you sure you want to Reset"];
NSString *ok = [NSString stringWithFormat:#"No"];
if(firstAlertView == nil)
{
firstAlertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
}
[firstAlertView show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (alertView == firstAlertView)
{
NSString *title= [NSString stringWithFormat:#"Warning"];
NSString *message = [NSString stringWithFormat:#"Are you sure you want to Reset"];
NSString *ok = [NSString stringWithFormat:#"No"];
if(secondAlertView == nil)
{
secondAlertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:ok otherButtonTitles:#"Yes",nil];
}
[secondAlertView show];
}
else if(alertView == secondAlertView)
{
[self resetArray];
}
}
and in dealloc method please release the allocated UIAlertviews.
Hope i am clear to you.
Thanks,
Jim.