I know this was already asked on here and I have used code from it but I still can't pass value of double grandTotal (from InitialStoreViewController) to double isSomethingEnabled (in ViewController). Here are my view controller files:
InitialStoreViewController.h
#import <UIKit/UIKit.h>
#import "InitialStoreViewController.h"
#import "ViewController.h"
#interface InitialStoreViewController : UITableViewController<UITextFieldDelegate>
{
// TargetViewCon TargetViewController *targetView;
IBOutlet UILabel *peasLabel;
IBOutlet UILabel *eggsLabel;
IBOutlet UILabel *milkLabel;
IBOutlet UILabel *beansLabel;
// requested amounts of each product
int peasAmountInt;
int eggsAmountInt;
int milkAmountInt;
int beansAmountInt;
double peasTotal;
double eggsTotal;
double milkTotal;
double beansTotal;
double grandTotal;
}
- (IBAction)peasStepper:(UIStepper *)sender;
- (IBAction)eggsStepper:(UIStepper *)sender;
- (IBAction)milkStepper:(UIStepper *)sender;
- (IBAction)beansStepper:(UIStepper *)sender;
- (IBAction)calcTotal:(UIBarButtonItem *)sender;
#property double price;
#property double priceToPass;
//this method is
//- (void) stepperAction: (UIStepper*)stepper toLabel: (UILabel*)label;
#end
InitialStoreViewController.m
#import "InitialStoreViewController.h"
#import "ViewController.h"
#import "Product.h"
#implementation InitialStoreViewController
- (void)viewDidLoad
{
//sunday:
[super viewDidLoad];
}
- (IBAction)peasStepper:(UIStepper *)sender
{
peasAmountInt = (int) sender.value;
NSLog(#"Peas Amount: %i", peasAmountInt);
peasLabel.text = [NSString stringWithFormat:#"%i", peasAmountInt];
//Initiating object of class Product
Product *peas = [[Product alloc]init];
peas.amountInt = peasAmountInt;
peasTotal = [peas multiplyAmount: peas.amountInt byPrice:0.95];
NSLog(#"Total amount for peas: %f", peasTotal);
grandTotal = peasTotal + eggsTotal + milkTotal + beansTotal;
NSLog(#"TOTAL Amount: %f", grandTotal);
}
- (IBAction)eggsStepper:(UIStepper *)sender
{
eggsAmountInt = (int) sender.value;
NSLog(#"Eggs Amount: %i", eggsAmountInt);
eggsLabel.text = [NSString stringWithFormat:#"%i", eggsAmountInt];
//Initiating object of class Product
Product *eggs = [[Product alloc]init];
eggs.amountInt = eggsAmountInt;
eggsTotal = [eggs multiplyAmount: eggs.amountInt byPrice:2.10];
NSLog(#"Total amount for eggs: %f", eggsTotal);
grandTotal = peasTotal + eggsTotal + milkTotal + beansTotal;
NSLog(#"TOTAL Amount: %f", grandTotal);
}
- (IBAction)milkStepper:(UIStepper *)sender
{
milkAmountInt = (int) sender.value;
NSLog(#"Milk Amount: %i", milkAmountInt);
milkLabel.text = [NSString stringWithFormat:#"%i", milkAmountInt];
//Initiating object of class Product
Product *milk = [[Product alloc]init];
milk.amountInt = milkAmountInt;
milkTotal = [milk multiplyAmount: milk.amountInt byPrice:1.30];
NSLog(#"Total amount for milk: %f", milkTotal);
grandTotal = peasTotal + eggsTotal + milkTotal + beansTotal;
NSLog(#"TOTAL Amount: %f", grandTotal);
}
- (IBAction)beansStepper:(UIStepper *)sender
{
beansAmountInt = (int) sender.value;
NSLog(#"Beans Amount: %i", beansAmountInt);
beansLabel.text = [NSString stringWithFormat:#"%i", beansAmountInt];
//Initiating object of class Product
Product *beans = [[Product alloc]init];
beans.amountInt = beansAmountInt;
beansTotal = [beans multiplyAmount: beans.amountInt byPrice:1.30];
NSLog(#"Total amount for beans: %f", beansTotal);
grandTotal = peasTotal + eggsTotal + milkTotal + beansTotal;
NSLog(#"TOTAL Amount: %f", grandTotal);
}
- (IBAction)calcTotal:(UIBarButtonItem *)sender
{
grandTotal = peasTotal + eggsTotal + milkTotal + beansTotal;
NSLog(#"TOTAL Amount: %f", grandTotal);
}
//sunday
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"showDetailSegue"]){
UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
ViewController *controller = (ViewController *)navController.topViewController;
// controller.isSomethingEnabled = YES;
controller.isSomethingEnabled = &(grandTotal);
}
}
#end
ViewController.h
#import <UIKit/UIKit.h>
#import "InitialStoreViewController.h"
#interface ViewController : UIViewController <UIPickerViewDataSource,
UIPickerViewDelegate>
{
NSArray *news;
NSMutableData *data;
double isSomethingEnabled;
}
#property(nonatomic) double *totalLabelDouble;
#property(nonatomic) double *isSomethingEnabled;
#property (nonatomic, strong) NSArray *currencyArray;
#property (weak, nonatomic) IBOutlet UILabel *totalLabel;
#property (weak, nonatomic) IBOutlet UIPickerView *picker;
#end
ViewController.m
#import "ViewController.h"
#import "Product.h"
#import "InitialStoreViewController.h"
#interface ViewController ()
#end
#implementation ViewController
//double totalLabelDouble = double isSomethingEnabled;
#synthesize currencyArray, totalLabel, picker;
- (void)viewDidLoad
{
[super viewDidLoad];
//checking if value of grandTotal was passed to this view controller:
NSLog(#"HHHHHHHHHHHHHHHHHHHHHHHHHHHH :%f", isSomethingEnabled);
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://www.apilayer.net/api/live?access_key=0b8125d8ca8e2801643e360440409165"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view, typically from a nib.
//connection:willCacheResponse
//connection:didReceiveResponse
//connection:didReceiveData
//connectionDidFinishLoading
//connection:didFailWithError
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news= [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//[mainTableView reloadData];
NSLog(#"RAW DATA Marcin %#", data);
//NEW Stuff:
// Now create a NSDictionary from the JSON data
// NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Create a new array to hold the locations
// NSMutableArray *locations = [[NSMutableArray alloc] init];
// Get an array of dictionaries with the key "locations"
// NSArray *array = [jsonDictionary objectForKey:#"USDGBP"];
// for (id USDGBP in array)
//NSLog(#"VALUEEEEEE %#", array);
// NSLog (#"%#", [[arrayController selectedObjects] valueForKey:#"USDGBP"]);
NSString *json_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data AS STRING %#", json_string);
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
double usdgbpValue = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
//NSArray *xxx = [jsonDict[#"quotes"][#"USDGBP"] array];
//NSLog(#"VALUEEEEEE %#", xxx);
NSDictionary *jsonDict2 = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//double usdgbpValue2 = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
NSArray *CurrencyArray = [jsonDict2 objectForKey:#"quotes"];
NSLog(#"VALUE %#", CurrencyArray);
//below causing crash
//currencyArray = [[NSArray alloc]initWithArray:CurrencyArray];
//currencyArray = CurrencyArray;
//double usdgbpValue3 = [NSArray[#"USDGBP"]currencyArray];
NSLog(#"USDGBP :%f", usdgbpValue);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//here to display message that internet connection is needed
}
//Creating product classes
//static Product *peas = nil;
//peas = [[Product alloc]init];
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UIPickerView Datasource & Delegate Methods
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [currencyArray count];
}
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
__TVOS_PROHIBITED
{
return currencyArray[row];
}
/// NEW CODE
//NSLog(#"USDGBP :%f", isSomethingEnabled);
//UILabel totalLabel.text = [NSString stringWithFormat: #"%d",
//isSomethingEnabled];
#end
When I run the code I get value for grandTotal but below code shows 0.000 for isSomethingEnabled:
NSLog(#"HHHHHHHHHHHHHHHHHHHHHHHHHHHH :%f", isSomethingEnabled);
Related
I have an Array with 10 Objects. I take the first Object and put it into my Label with a String.
Then I want to have a Method that increases the objectAtIndex by 1.
This is my Code :
//.m
#interface GameViewController () {
NSInteger _labelIndex;
}
#property (nonatomic) NSArray *playerArray;
#property (nonatomic) NSString *playerLabel;
- (void)viewDidLoad {
[super viewDidLoad];
self.playerArray = [NSArray arrayWithObjects:#"FIRST", #"SECOND", #"THIRD", #"FOURTH", #"FIFTH", #"SIXT", #"SEVENTH", #"EIGTH", #"NINTH", #"TENTH", nil];
_labelIndex = 0;
[self updateTurnLabel];
self.turnLabel.text = [NSString stringWithFormat:#"YOUR %# DRAW?", self.playerLabel];
}
Here I call the Method i another Method:
-(void) flipDraws {
self.boardView.userInteractionEnabled = NO;
[self updateTurnLabel];
CardView *cv1 = (CardView *) self.turnedDrawViews[0];
CardView *cv2 = (CardView *) self.turnedDrawViews[1];
}
This is my Method:
-(void) updateTurnLabel {
self.playerLabel = [self.playerArray objectAtIndex:_labelIndex % self.playerArray.count]; _labelIndex++;
}
I tried it with a for Loop but nothing happened. I tried it with just set the objectAtIndex:1 but my Method was not called.
What I am doing wrong?
{
int a;
}
- (void)viewDidLoad {
[super viewDidLoad];
a = 0;
self.playerArray = [NSArray arrayWithObjects:#"FIRST", #"SECOND", #"THIRD", #"FOURTH", #"FIFTH", #"SIXT", #"SEVENTH", #"EIGTH", #"NINTH", #"TENTH", nil];
self.playerLabel = [self.playerArray objectAtIndex:a];
self.turnLabel.text = [NSString stringWithFormat:#"YOUR %# DRAW?", self.playerLabel];
}
-(void) updateTurnLabel {
a +=1;
if (!a<[playerArray count])
{
a = 0;
}
self.playerLabel = [self.playerArray objectAtIndex:a];
}
call self.turnLabel.text = [NSString stringWithFormat:#"YOUR %# DRAW?", self.playerLabel]; after [self updateTurnLabel];
What are you adding +1 to in the method objectAtIndex:.
You should be maintaining a variable which tracks the current index being used, then in your method use this :
-(void) updateTurnLabel {
self.playerLabel = [self.playerArray objectAtIndex:currentIndex+1];
}
So i recently implemented parallax images into my app which works great, however this has broken a button which calls a method.
Here is a picture of my storyboard:
http://imgur.com/uIonWrK
Here is my .h code:
#interface _01FirstViewController : UIViewController <UITextFieldDelegate, UIAccelerometerDelegate>{
UIAccelerometer *accelerometer;
float xoof;
float yoff;
float xvelocity;
float yvelocity;
float xaccel;
float yaccel;
}
#property (nonatomic, retain) UIAccelerometer *accelerometer;
#property (weak, nonatomic) IBOutlet UIScrollView *BGScrollView;
#property (weak, nonatomic) IBOutlet UIButton *Track;
#property (weak, nonatomic) IBOutlet UITextField *trackingNumber;
#property (strong, nonatomic) NSDictionary *posts;
#property (strong,nonatomic) NSString *TrackPoint;
#property (strong,nonatomic) NSArray *Path;
#property (strong,nonatomic) NSString *documentFolder;
#property (strong,nonatomic) NSString *filePath;
-(void)parseTrackNo;
-(void)reloadTrackingNumber;
Here is the relevant parts of the .m:
- (void)viewDidLoad
{
_BGScrollView.contentSize = CGSizeMake(_BGScrollView.frame.size.width+30,_BGScrollView.frame.size.width+30);
self.accelerometer = [UIAccelerometer sharedAccelerometer];
self.accelerometer.updateInterval = 0.03;
self.accelerometer.delegate = self;
[NSTimer scheduledTimerWithTimeInterval:-1 target:self selector:#selector(tick) userInfo:nil repeats:YES];
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
float xx = -acceleration.x;
float yy = (acceleration.y + 0.5f) *2.0f;
float acceldirX;
if (xvelocity * -1.0f >0){
acceldirX = 1.0;
}
else {
acceldirX = -1.0;
}
float newdirX;
if (xx > 0){
newdirX = 1.0;
}
else {
newdirX = -1.0;
}
float acceldirY;
if (yvelocity * -1.0f >0){
acceldirY = 1.0;
}
else {
acceldirY = -1.0;
}
float newDirY;
if (yy > 0){
newDirY = 1.0;
}
else {
newDirY = -1.0;
}
if (acceldirX == newdirX) xoof = acceleration.x * 30;
if (acceldirY == newDirY) yoff = acceleration.y *30;
}
This is the button that has stopped calling the method:
- (IBAction)Track:(id)sender {
[self parseTrackNo]; //Not calling method
NSLog(#"Button Pressed"); //This gets logged correctly
}
I have tried removing all code changes so i suspect it is something to do with the button being nested inside the view in the storyboard or the delegate changes.
Can anyone point me in the correct direction?
EDIT as requested the code for parseTrackingNo (note this was working perfectly until the parallax changes):
-(void)parseTrackNo
{
_01AppDelegate *appDelegate = (_01AppDelegate *)[[UIApplication sharedApplication] delegate];
//Get Tracking Number from textField
appDelegate.TrackingNumber = _trackingNumber.text;
//Check String isn't empty
if ([_trackingNumber.text isEqual: #""]){
} else{
//Check against Royal Mail API
NSString *trackingURL = [NSString stringWithFormat:#"%#%#", #"http://api.e44.co/tracktrace/", appDelegate.TrackingNumber];
NSURL *royalMail = [NSURL URLWithString:trackingURL];
//Return results
NSData *royalMailResults = [NSData dataWithContentsOfURL:royalMail];
//Parse JSON results
if(royalMailResults != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:royalMailResults options:NSJSONReadingMutableContainers error:&error];
if (error == nil)
//Convert to dictionary/array
self.posts = (NSDictionary *)result;
NSArray *trackRecords = _posts[#"trackRecords"];
//Return keys from posts (Dict)
NSString *response = [self.posts valueForKeyPath:#"response"];
NSLog(#"Response: %#", response);
NSString *returnedTrackingNumber = [self.posts valueForKeyPath:#"trackingNumber"];
NSLog(#"Returned tracking number: %#", returnedTrackingNumber);
NSString *delivered = [self.posts valueForKeyPath:#"delivered"];
NSLog(#"delivered: %#", delivered);
NSString *signature = [self.posts valueForKeyPath:#"signature"];
NSLog(#"Signature: %#", signature);
//Track Records
NSString *Date = [trackRecords valueForKeyPath:#"date"];
NSLog(#"date: %#", Date);
NSString *Time = [trackRecords valueForKeyPath:#"time"];
NSLog(#"time: %#", Time);
NSString *Status = [trackRecords valueForKeyPath:#"status"];
NSLog(#"status: %#", Status);
appDelegate.LocationData = [[trackRecords valueForKey:#"trackPoint"] componentsJoinedByString:#""];
NSLog(#"GeoLocation: %#", appDelegate.LocationData);
//Check for Errors returned
if ([self.posts objectForKey:#"errorMsg"]) {
NSLog(#"ERROR MOTHERFUCKER");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"It appears that you have entered an incorrect tracking number"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alert show];
} else {
[self performSegueWithIdentifier:#"addPackageSegue" sender:self];
}
}
}
}
I want to make a synchronized show lyric app and all lyric shown on a UITextView. In order to highlight current lyric I add background color to NSAttributedString of UITextView. All NSRange of lines stored in a NSArray.
My code is pretty simple, when button tapped move the highlight line down (via set contentOffset of UITextView). But here a strange problem occurred. In the beginning, the UITextView scroll properly but when contentOffset of UITextView greater then its frame.size.height it was fixed.
Here is my code:
//View controller
#import "ViewController.h"
#interface ViewController () {
NSUInteger globelIndex;
NSArray *textRanges;
NSMutableAttributedString *attributedText;
}
#property (weak, nonatomic) IBOutlet UITextView *lyricView;
#property (strong, nonatomic) NSTimer *mainTimer;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *rawText = [self readFile];
globelIndex = 0;
[self initTextLines:rawText];
attributedText = [[NSMutableAttributedString alloc] initWithString:rawText
attributes:#{NSBackgroundColorAttributeName: [UIColor orangeColor]}];
self.lyricView.attributedText = [attributedText copy];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)manualNextLine:(UIButton *)sender {
[self updateTextView];
}
- (IBAction)autoNextLineUsingNSTimer:(UIButton *)sender {
self.mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateTextView) userInfo:nil repeats:YES];
}
- (void)updateTextView {
if (self.lyricView.contentOffset.y >= self.lyricView.contentSize.height &&
self.mainTimer)
{
self.mainTimer = nil;
return;
}
NSMutableAttributedString *mat = [attributedText mutableCopy];
NSValue *value = [textRanges objectAtIndex:globelIndex];
[mat addAttribute:NSBackgroundColorAttributeName value:[UIColor whiteColor] range:[value rangeValue]];
self.lyricView.attributedText = [mat copy];
globelIndex += 1;
// self.textView.contentOffset = CGPointMake(self.textView.contentOffset.x, self.textView.contentOffset.y + 24);
// [self.textView scrollRangeToVisible:[value rangeValue]];
CGPoint newOffset = CGPointMake(self.lyricView.contentOffset.x, self.lyricView.contentOffset.y + 20);
[self.lyricView setContentOffset:newOffset animated:NO];
NSLog(#"[%# %#] h: %f b: %f a: %f", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.lyricView.contentSize.height, newOffset.y, self.lyricView.contentOffset.y);
}
#pragma mark - helper
- (void)initTextLines:(NSString *)rawText {
NSMutableArray *result = [#[] mutableCopy];
NSArray *t = [rawText componentsSeparatedByString:#"\r\n"];
__block int index = 0;
[t enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *s = obj;
NSRange range = NSMakeRange(index, s.length + 2);
[result addObject:[NSValue valueWithRange:range]];
index += s.length + 2;
}];
textRanges = [result copy];
}
- (NSString *)readFile {
NSError *error = nil;
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:#"二人の季節が-ささきのぞみ-想い" withExtension:#"lrc"];
NSString *content = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&error];
if (error) {
if (DEBUG) NSLog(#"[%# %#] Error: %#", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
abort();
}
return content;
}
#end
All my code was in ViewController and StoryBoard has two UIButton and a UITextView.
What I wonder is "Why the UITextView.contentOffset cannot change when it greater than some size".
Maybe rewrite setContentOffset:animated is helpful for you!
Here is some sample code which you can borrow:
https://github.com/360/Three20/blob/master/src/Three20UI/Sources/TTTextView.m
#import "Three20UI/TTTextView.h"
// UI
#import "Three20UI/UIViewAdditions.h"
#implementation TTTextView
#synthesize autoresizesToText = _autoresizesToText;
#synthesize overflowed = _overflowed;
- (void)setContentOffset:(CGPoint)offset animated:(BOOL)animated {
if (_autoresizesToText) {
if (!_overflowed) {
// In autosizing mode, we don't ever allow the text view to scroll past zero
// unless it has past its maximum number of lines
[super setContentOffset:CGPointZero animated:animated];
} else {
// If there is an overflow, we force the text view to keep the cursor at the bottom of the
// view.
[super setContentOffset: CGPointMake(offset.x, self.contentSize.height - self.height)
animated: animated];
}
} else {
[super setContentOffset:offset animated:animated];
}
}
#end
Now i am updating the code with the perfect output. This may help my friends to place the correct markers.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
placevcViewController.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import
#import "fetchurl.h"
#import
#interface placevcViewController : UIViewController
{
CLLocationDegrees lat;
CLLocationDegrees lng;
CLLocationCoordinate2D local;
}
-(id)init;
-(void)location:(CLLocationManager *)address;
#property (nonatomic, strong) NSDictionary *location;
#property (strong, nonatomic) UITextField *addressfeild;
#property (strong, nonatomic) fetchurl *fu;
#property (strong, nonatomic) GMSMapView *map;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) GMSCameraPosition *camera;
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
placevcViewController.m
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import "placevcViewController.h"
#interface placevcViewController ()
#end
#implementation placevcViewController
#synthesize addressfeild, map,fu,locationManager,camera;
-(id)init
{
self = [super init];
location = [[NSDictionary alloc] initWithObjectsAndKeys:#"0.0",#"lat",#"0.0",#"lng",#"Null Island",#"adress",#"NULL Home",#"name", nil];
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
lat = locationManager.location.coordinate.latitude;
lng = locationManager.location.coordinate.longitude;
local = CLLocationCoordinate2DMake(lat, lng);
fu = [[fetchurl alloc]init];
camera = [GMSCameraPosition cameraWithLatitude:lat longitude: lng zoom:12];
map = [GMSMapView mapWithFrame:CGRectMake(0, 60, 320, 480) camera:camera];
[self.view addSubview:map];
map.settings.myLocationButton = YES;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(200, 65, 100, 40);
[button setTitle:#"SEARCH" forState:UIControlStateNormal];
[button addTarget:self action:#selector(search:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
addressfeild = [[UITextField alloc] initWithFrame:CGRectMake(10, 68, 200, 30)];
addressfeild.placeholder = #"SEARCH";
[addressfeild setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:addressfeild];
}
-(IBAction)search:(id)sender
{
[self location:str1];
}
-(void)location:(NSString *)address
{
NSString *baseUrl =#"https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
NSString *url = [NSString stringWithFormat:#"%#location=%#&radius=10000&name=dominos&sensor=false&key=AIzaSyCczXEpxw19qAXQMEUUA98OsMaOESNSOjM",baseUrl,address];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *queryUrl = [NSURL URLWithString:url];
NSLog(#"query url%#",queryUrl);
dispatch_async(dispatch_get_main_queue(), ^{
NSData *data = [NSData dataWithContentsOfURL:queryUrl];
[self fetchData:data];
});
}
-(void)fetchData:(NSData *)data
{
NSString *data1 = [NSString stringWithUTF8String:[data bytes]];
// NSLog(#"Response data: %#", data1);
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* results =[json objectForKey:#"results"];
//NSLog(#"Data is:%#" ,results);
for (int i = 0;i <[results count]; i++) {
NSDictionary *result = [results objectAtIndex:i];
// NSLog(#"Data is %#", result);
NSString *address = [result objectForKey:#"vicinity"];
// NSLog(#"Address is %#", address);
NSString *name = [result objectForKey:#"name"];
//NSLog(#"name is %#", name);
NSDictionary *geometry = [result objectForKey: #"geometry"];
NSDictionary *locations = [geometry objectForKey:#"location"];
NSString *lat =[locations objectForKey:#"lat"];
NSString *lng =[locations objectForKey:#"lng"];
//NSLog(#"longitude is %#", lng);
NSDictionary *gc = [[NSDictionary alloc]initWithObjectsAndKeys:lat,#"lat",lng,#"lng",address,#"address",name,#"name", nil];
location = gc;
double lat1 = [[location objectForKey:#"lat"] doubleValue];
NSLog(#"Marker position%f",lat1);
double lng1 = [[location objectForKey:#"lng"] doubleValue];
NSLog(#"Marker position%f",lng1);
GMSMarker *marker = [[GMSMarker alloc]init];
CLLocationCoordinate2D local = CLLocationCoordinate2DMake(lat1, lng1);
marker.position = local;
marker.title = [ location objectForKey:#"name"];
NSLog(#"Address is %#",marker.title);
marker.snippet = [location objectForKey:#"address"];
marker.map = map;
GMSCameraUpdate *cams = [GMSCameraUpdate setTarget:local zoom:12];
[map animateWithCameraUpdate:cams];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I am facing trouble with the functions which i bolded up. Actually i want to pass the co-ordinates of my current location from placevcViewController.m to fetchurl.m through a function -(void)location:(CLLocationManager *)address withCallback:(SEL)sel withDelegate: (id)delegate; , but somehow it is not working. Either the function is incorrect or i am not using the correct data type for fetching the co-ordinates.
Updates :
I have update the above code in fetchurl.m file(you can c ** there the code within the stars is upadted ) , and the updation is helping me to get the array of multiple locations. But now i am not getting how to add the marker on each location.
To use the delegate-protocol pattern successfully, you need some additional setup:
PlacevcViewController.h needs to define both a delegate property, and define the protocol:
#property (nonatomic, assign) id delegate;
//at the bottom of your file, below the #interface ... #end
#protocol nameOfYourProtocol <NSObject>
-(void)methodForDoingSomething:(SomeClass*)argument;
#end
Then within PlacevcViewController.m you can call your delegate method like this:
[self.delegate methodForDoingSomething:anArgument];
Then you assign your delegate and implement the method in the target class (fetchUrl.h in your case)
//declare conformity to the protocol like this in the header file
#interface fetchurl : NSObject <nameOfYourProtocol>
and finally in the fetchUrl.m file:
//assign the delegate to self when creating an instance of fetchUrl
fu = [[fetchUrl alloc] init];
[fu setDelegate:self];
//implement the delegate method
- (void)methodForDoingSomething:(SomeClass*)argument {
//your code goes here
}
While there is nothing right or wrong about using the delegate-protocol pattern, from what I can tell of your example a simpler approach might be to just define a method within fetchUrl that returns the items you need and let the owner of that instance of fetchUrl handle it. ie:
- (NSDictionary*)fetchData:(NSData*)data {
//do the work and create a dictionary
//return theDictionary
}
and then just consume the result in your placevcViewController:
NSDictionary* results = [fu fetchData:someData];
//now work with the results
i am developing very simple quiz app
In viewDidLoad i am adding objects in myarray
where ever i nslog myarray values it works fine
but if i try this inside ibaction methods all objects becomes zombie
for 2 days i am stuck in this but can't find it what is wrong.
quiz.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#class dbVals;
#class viewTransition;
#class AppDelegate;
#interface quiz : UIViewController
{
NSMutableArray *myarray;
IBOutlet UITextView *questionTextView_;
IBOutlet UIButton *skipButton_;
IBOutlet UIButton *optionAButton_;
IBOutlet UIButton *optionBButton_;
IBOutlet UIButton *optionCButton_;
NSString *correctAnswer;
int questionNumber;
int score;
IBOutlet UILabel *scoreLabel_;
int totalQuestions;
}
-(void)populate:(int)number;
//#property(nonatomic, retain) NSMutableArray *myarray;
#property (retain, nonatomic) IBOutlet UITextView *questionTextView;
#property (retain, nonatomic) IBOutlet UIButton *skipButton;
#property (retain, nonatomic) IBOutlet UIButton *optionAButton;
#property (retain, nonatomic) IBOutlet UIButton *optionBButton;
#property (retain, nonatomic) IBOutlet UIButton *optionCButton;
#property (retain, nonatomic) IBOutlet UILabel *scoreLabel;
- (IBAction)optionsToAnswer:(id)sender;
- (IBAction)zzz:(id)sender;
#end
quiz.m
#import "quiz.h"
#import "DbVals.h"
#import "viewTransition.h"
#import "AppDelegate.h"
#implementation quiz
#synthesize skipButton=skipButton_;
#synthesize optionAButton=optionAButton_;
#synthesize optionBButton=optionBButton_;
#synthesize optionCButton=optionCButton_;
#synthesize scoreLabel=scoreLabel_;
#synthesize questionTextView=questionTextView_;
//#synthesize myarray;
- (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)createEditableCopyOfDatabaseIfNeeded
{
//NSLog(#"Creating editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
+(sqlite3 *) getNewDBConnection
{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
//NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
return newDBconnection;
}
- (void)viewDidLoad
{
[super viewDidLoad];
questionNumber = 0;
score = 0;
[self createEditableCopyOfDatabaseIfNeeded];
sqlite3 *dbc = [quiz getNewDBConnection];
sqlite3_stmt *statement = nil;
const char *sqlSelect = "select * from QnA ORDER BY RANDOM()";
if(sqlite3_prepare_v2(dbc, sqlSelect, -1, &statement, NULL)!=SQLITE_OK)
{
NSAssert1(0, #"Error Preparing Statement", sqlite3_errmsg(dbc));
}
else
{
myarray = [[NSMutableArray alloc]init];
while(sqlite3_step(statement)==SQLITE_ROW)
{
NSString *q = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
NSString *o = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
NSString *a = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 2)];
DbVals *dbValsObj = [[DbVals alloc]init];
[dbValsObj setValsOfQuestions:q options:o answer:a];
[myarray addObject:dbValsObj];
[dbValsObj release];
}
}
sqlite3_finalize(statement);
//[self populate:questionNumber];
}
-(void)populate:(int)number
{
/*[scoreLabel_ setText:[NSString stringWithFormat:#"%d",score]];
AppDelegate *appDel = [[UIApplication sharedApplication] delegate];
[appDel setFinalScore:[NSString stringWithFormat:#"%d",score]];
if(number < [myarray count])
{
DbVals *dbv1 = [myarray objectAtIndex:number];
[questionTextView_ setText:[dbv1 getQuestions]];
NSString *joinedOptions = [dbv1 getOptions];
NSArray *splitOptions = [joinedOptions componentsSeparatedByString:#","];
[optionAButton_ setTitle:[splitOptions objectAtIndex:0] forState:UIControlStateNormal];
[optionBButton_ setTitle:[splitOptions objectAtIndex:1] forState:UIControlStateNormal];
[optionCButton_ setTitle:[splitOptions objectAtIndex:2] forState:UIControlStateNormal];
correctAnswer = [dbv1 getAnswer];
}
else
{
//viewTransition *vt = [[viewTransition alloc]init];
[viewTransition viewsTransitionCurrentView:self toNextView:#"result"];
//[vt release];
}*/
}
- (void)viewDidUnload
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<u><u><u><u><><><><><><><><><><><>");
}
[self setQuestionTextView:nil];
[questionTextView_ release];
questionTextView_ = nil;
[self setQuestionTextView:nil];
[skipButton_ release];
skipButton_ = nil;
[self setSkipButton:nil];
[optionAButton_ release];
optionAButton_ = nil;
[self setOptionAButton:nil];
[optionBButton_ release];
optionBButton_ = nil;
[self setOptionBButton:nil];
[optionCButton_ release];
optionCButton_ = nil;
[self setOptionCButton:nil];
[scoreLabel_ release];
scoreLabel_ = nil;
[self setScoreLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<d><d><d><d><d><><><><><><><><><><>");
}
[questionTextView_ release];
[skipButton_ release];
[optionAButton_ release];
[optionBButton_ release];
[optionCButton_ release];
[scoreLabel_ release];
[myarray release];
[super dealloc];
}
- (IBAction)optionsToAnswer:(id)sender
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"six");
}
if(sender == skipButton_)
{
//questionNumber++;
//[self populate:questionNumber];
/*[UIView animateWithDuration:5 delay:0 options: UIViewAnimationCurveEaseOut
animations:
^{
[UIView setAnimationTransition:103 forView:self.view cache:NO];
}
completion:
^(BOOL finished)
{
}
];*/
}
if(sender == optionAButton_)
{
/*NSString *one = #"1";
if([correctAnswer isEqualToString:one])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionBButton_)
{
/*NSString *two = #"2";
if([correctAnswer isEqualToString:two])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionCButton_)
{
/*NSString *three = #"3";
if([correctAnswer isEqualToString:three])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
}
- (IBAction)zzz:(id)sender
{
}
#end
dbVals.h
#import <Foundation/Foundation.h>
#interface DbVals : NSObject
{
NSString *questions_;
NSString *options_;
NSString *answer_;
// NSString *hint;
// NSString *mode;
}
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer;
-(NSString*)getQuestions;
-(NSString*)getOptions;
-(NSString*)getAnswer;
dbVals.m
#import "DbVals.h"
#implementation DbVals
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
questions_ = questions;
options_ = options;
answer_ = answer;
}
-(NSString*)getQuestions
{
return questions_;
}
-(NSString*)getOptions
{
return options_;
}
-(NSString*)getAnswer
{
return answer_;
}
#end
Your dbVals.m setVals isn't retaining the parameters. This obviously means, everything inside becomes deallocated once the function scope ends.
Try changing it to something like
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
[questions_ release];
[options_ release];
[answer_ release];
questions_ = [questions copy];
options_ = [options copy];
answer_ = [answer copy];
}