Use ios7 CoreLocation to create Google Maps link - google-maps

New to ios developement and need a little help.
I am trying to use CoreLocation to load the users current location to a UITextField formatted as a Google Maps link ( http://maps.google.com/maps?q=loc:userLatitude,-userLongitude ) so I can share in sms.Can anyone suggest or point me to a example I can look at.
Please and Thanks.
Guess I'm not being clear enough.I want to use corelocation to pass the current lat and long to this string (http:/maps.google.com/maps?q=loc:currentLat,-currentLong) and load it to a UITextField.
ie: if you were in Toronto the uitextField would have this link
http://maps.google.com/maps?q=loc:43.653433,-79.380341
For anyone thats interested I worked it out myself.

#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) CLLocationManager *manager;
#property (strong, nonatomic) IBOutlet UITextField *MyLocation;
#property (strong, nonatomic) IBOutlet UILabel *addressLabel;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self startLocations];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Location Manager
- (CLLocationManager *)manager {
if (!_manager) {
_manager = [[CLLocationManager alloc]init];
_manager.delegate = self;
_manager.desiredAccuracy = kCLLocationAccuracyBest;
}
return _manager;
}
- (void)startLocations {
// create and start the location manager
[self.manager startUpdatingLocation];
}
- (void)stopLocations {
// create and start the location manager
[self.manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"Error: %#", [error description]);
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// grab current location and display it in a label
CLLocation *currentLocation = [locations lastObject];
NSString *here = [
NSString stringWithFormat:#"http://maps.google.com/maps?q=loc:
%f,%f",currentLocation.coordinate.
latitude,currentLocation.
coordinate.longitude];
self.MyLocation.text = here;
// and update our Map View
[self updateMapView:currentLocation];
}
#pragma mark - Map Kit
- (void)updateMapView:(CLLocation *)location {
// create an address from our coordinates
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks,
NSError *error)
{
CLPlacemark *placemark = [placemarks lastObject];
NSString *address = [NSString stringWithFormat:#"%#, %#, %#,
%#, %#, %#", placemark.subThoroughfare,placemark.
thoroughfare, placemark.locality, placemark.administrativeArea,
placemark.postalCode,placemark.
ISOcountryCode];
if (placemark.thoroughfare != NULL) {
self.addressLabel.text = address;
} else {
self.addressLabel.text = #"";
}
}];
[self stopLocations];}
#end

Related

How to parse html tag url and make it clickable in a label

I need to parse a html tag. For exemple:
<a href=“http://www.google.it”>MY LINK</a>
So, how can I detect this link, and make it clickable in a label? Only the link clickable.
Thanks
You can just use TextView. With textView you will set that the attributedText has an attribute that is the link you want
NSString *url = #"https://www.stackoverflow.com";
NSString *stringLink = #"My link";
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:stringLink attributes:nil];
[attrString addAttribute:NSLinkAttributeName value:url range:NSMakeRange(0, [attrString.string length])];
self.textView.attributedText = attrString;
Edit:
Make sure to format correctly your String to be sure to catch your url after "href=\"" and the stringLink after ">" character.
Try this way In ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITextView *textView;
#end
And ViewController.m
#import "ViewController.h"
#interface ViewController ()<UITextViewDelegate>
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITapGestureRecognizer *tapGesture =[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapOnTextView)];
[self.textView addGestureRecognizer:tapGesture];
[tapGesture setNumberOfTapsRequired:1];
[self.view addSubview:self.textView];
self.textView.delegate=self;
NSString * testStr=#"The world’s most popular camera is more advanced than ever. The 12-megapixel iSight camera captures sharp, detailed photos. It takes brilliant 4K video, up to four times the resolution of 1080p HD video. https://www.google.com/gmail/about/# iPhone 6s also takes selfies worthy of a self-portrait with the new 5-megapixel FaceTime HD camera. And it introduces Live Photos, a new way to relive your favourite memories. It captures the moments just before and after your picture and sets it in motion with just the press of a finger.";
self.textView.text = testStr;
self.textView.dataDetectorTypes = UIDataDetectorTypeLink;
}
- (void)openScheme:(NSString *)scheme {
UIApplication *application = [UIApplication sharedApplication];
NSURL *URL = [NSURL URLWithString:scheme];
if ([application respondsToSelector:#selector(openURL:options:completionHandler:)]) {
[application openURL:URL options:#{}
completionHandler:^(BOOL success) {
NSLog(#"Open %#: %d",scheme,success);
}];
} else {
BOOL success = [application openURL:URL];
NSLog(#"Open %#: %d",scheme,success);
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)tapOnTextView
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.textView.text];
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
[detector enumerateMatchesInString:self.textView.text options:kNilOptions range:NSMakeRange(0, [self.textView.text length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSLog(#"Values: %#", result);
if (result.resultType == NSTextCheckingTypeLink)
{
NSLog(#"matched: %#",result.URL);
[self openScheme:[result.URL absoluteString]];
}
}];
self.textView.attributedText=attributedString;
}

How to put JSON element into UITextView?

I have a MySQL database and a PHP script that work perfectly. However, I was wondering how I could get this data from JSON format to a UITextView. I also have a table being populated with 2 other JSON elements. Thanks!
TableInfo.h
#import <Foundation/Foundation.h>
#interface TableInfo : NSObject
#property (nonatomic, strong) NSString *Title;
#property (nonatomic, strong) NSString *SubTitle;
#property (nonatomic, strong) NSString *Description;
#end
HomeModel.h
#import <Foundation/Foundation.h>
#protocol HomeModelProtocol <NSObject>
- (void)itemsDownloaded:(NSArray *)items;
#end
#interface HomeModel : NSObject <NSURLConnectionDataDelegate>
#property (nonatomic, weak) id<HomeModelProtocol> delegate;
- (void)downloadItems;
#end
HomeModel.m
#import "HomeModel.h"
#import "TableInfo.h"
#interface HomeModel()
{
NSMutableData *_downloadedData;
}
#end
#implementation HomeModel
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:#"http://gandouhaiti.ueuo.com/service.php"];
NSLog(#"Donwload the JSON file");
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
NSLog(#"Create the request");
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
NSLog(#"Create the NSURLConnection");
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Inititalize the data object");
// Initialize the data object
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the newly downloaded data
[_downloadedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the locations
NSMutableArray *_locations = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new location object and set its props to JsonElement properties
TableInfo *newdata = [[TableInfo alloc] init];
newdata.Title = jsonElement[#"Title"];
newdata.SubTitle = jsonElement[#"SubTitle"];
newdata.description = jsonElement[#"Description"];
// Add this question to the locations array
[_locations addObject:newdata];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_locations];
}
}
#end
If you wan to display the JSON in UITextView in storyboard, kindly try the following:
#implementation ViewController
NSString * JSON;
-(void) viewDidLoad
{
JSON = //get data from remote;
NSString *stringForTextView = #"";
NSData *data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if([array count] >0)
{
for(NSDictionary *d in array)
{
stringForTextView = [NSString stringWithFormat:#"Title:%#\nSubTitle:%#\nDescription:%#\n", [d valueForKey:#"Title"], [d valueForKey:#"SubTitle"], [d valueForKey:#"Description"]];
}
}
_textView.text = stringForTextView;
}
#end

iOS JSON Parsing to tableview, incorrect rows

I am developing an iOS App, I have a tableview controller populated from a MySQL database. When I click on a raw a detailview appears showing data from the database, such as a master detail app. The problem is following:
1. When I run the app on the iPhone simulator, the app shows the three records from the mysql table, thats correct.
2. If I click on the first row, nothing happened.
3. If I click on the second or third row, the app opens the detailview, but the data don't correspond to the selected row(record).
4. I click on the back button of the detailview, and the app opens the masterview again.
5. Now if I click on the first row, the app opens the detailview, but as mentioned before, the detailview data don't correspond to the selected row(record) on the master view.
Here you have my viewcontroller code (master view):
//
// ViewController.m
//
#import "ViewController.h"
#import "DetailViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Areas";
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
NSURL *url = [NSURL URLWithString:#""];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (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:nil error:nil];
[mainTableView reloadData];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The download could not complete - please make sure you're connect to either 3G or WiFi" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}
-(int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(int)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if(cell==nil){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"name"];
cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"nombre"];
return cell;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.title =[[news objectAtIndex:indexPath.row]objectForKey:#"nombre"];
detailViewController.newsArticle = [news objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
And here the detailview code:
//
// DetailViewController.m
//
#import "DetailViewController.h"
#interface DetailViewController ()
#end
#implementation DetailViewController
#synthesize newsArticle;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
titleLabel.text = [newsArticle objectForKey:#"nombre"];
timeLabel.text = [newsArticle objectForKey:#"name"];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Any idea what I have done wrong??
Thank you
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.title =[[news objectAtIndex:indexPath.row]objectForKey:#"nombre"];
detailViewController.newsArticle = [news objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
You are using didDeselectRow which is called when a row is deselected and hence the wierd behaviour plus wrong data.. you have to use didSelectRow

View controller not in view hierarchy?

So I am trying to transition from one view controller to another with a segue programmatically so that I can only initialize it when a user needs to login. However, xcode keeps giving me the error that it is not in the view hierarchy and refuses to load to it.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#end
ViewController.m
#import "ViewController.h"
#import "API.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if (![[API sharedInstance] isAuthorized]) {
[self performSegueWithIdentifier:#"ShowLogin" sender:nil];
}// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
LoginScreen.h (the controller not in the hierarchy)
#import <UIKit/UIKit.h>
#interface LoginScreen : UIViewController
{
//the login form fields
IBOutlet UITextField *fldUsername;
IBOutlet UITextField *fldPassword;
}
//action for when either button is pressed
-(IBAction)btnLoginRegisterTapped:(id)sender;
#end
LoginScreen.m (the controller apparently not in the hierarchy)
#import "LoginScreen.h"
#import "UIAlertView+error.h"
#import "API.h"
#include <CommonCrypto/CommonDigest.h>
#define kSalt #"(protected value)"
#implementation LoginScreen
-(void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - View lifecycle
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(IBAction)btnLoginRegisterTapped:(UIButton*)sender {
//form fields validation
if (fldUsername.text.length < 4 || fldPassword.text.length < 4) {
[UIAlertView error:#"Enter username and password over 4 chars each."];
return;
}
//salt the password
NSString* saltedPassword = [NSString stringWithFormat:#"%#%#", fldPassword.text, kSalt];
//prepare the hashed storage
NSString* hashedPassword = nil;
unsigned char hashedPasswordData[CC_SHA1_DIGEST_LENGTH];
//hash the pass
NSData *data = [saltedPassword dataUsingEncoding: NSUTF8StringEncoding];
if (CC_SHA1([data bytes], [data length], hashedPasswordData)) {
hashedPassword = [[NSString alloc] initWithBytes:hashedPasswordData length:sizeof(hashedPasswordData) encoding:NSASCIIStringEncoding];
} else {
[UIAlertView error:#"Password can't be sent"];
return;
}
//check whether it's a login or register
NSString* command = (sender.tag==1)?#"register":#"login";
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:command, #"command", fldUsername.text, #"username", hashedPassword, #"password", nil];
//make the call to the web API
[[API sharedInstance] commandWithParams:params onCompletion:^(NSDictionary *json) {
//result returned
NSDictionary* res = [[json objectForKey:#"result"] objectAtIndex:0];
if ([json objectForKey:#"error"]==nil && [[res objectForKey:#"IdUser"] intValue]>0) {
[[API sharedInstance] setUser: res];
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//show message to the user
[[[UIAlertView alloc] initWithTitle:#"Logged in" message:[NSString stringWithFormat:#"Welcome %#",[res objectForKey:#"username"]] delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil] show];
} else {
//error
[UIAlertView error:[json objectForKey:#"error"]];
}
}];
}
#end
API.h (calling my web service)
#import "AFHTTPClient.h"
#import "AFNetworking.h"
typedef void (^JSONResponseBlock)(NSDictionary* json);
#interface API : AFHTTPClient
#property (strong, nonatomic) NSDictionary* user;
+(API*)sharedInstance;
//check whether there's an authorized user
-(BOOL)isAuthorized;
//send an API command to the server
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock;
-(NSURL*)urlForImageWithId:(NSNumber*)IdPhoto isThumb:(BOOL)isThumb;
#end
API.m (calling my web service)
#import "API.h"
//the web location of the service
#define kAPIHost #"(protected web address)"
#define kAPIPath #""
#implementation API
#synthesize user;
#pragma mark - Singleton methods
/**
* Singleton methods
*/
+(API*)sharedInstance {
static API *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:kAPIHost]];
});
return sharedInstance;
}
#pragma mark - init
//intialize the API class with the deistination host name
-(API*)init {
//call super init
self = [super init];
if (self != nil) {
//initialize the object
user = nil;
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:#"Accept" value:#"application/json"];
}
return self;
}
-(BOOL)isAuthorized {
return [[user objectForKey:#"IdUser"] intValue]>0;
}
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock {
NSData* uploadFile = nil;
if ([params objectForKey:#"file"]) {
uploadFile = (NSData*)[params objectForKey:#"file"];
[params removeObjectForKey:#"file"];
}
NSMutableURLRequest *apiRequest = [self multipartFormRequestWithMethod:#"POST" path:kAPIPath parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
if (uploadFile) {
[formData appendPartWithFileData:uploadFile name:#"file" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
}
}];
AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:#"error"]);
}];
[operation start];
}
-(NSURL*)urlForImageWithId:(NSNumber*)IdPhoto isThumb:(BOOL)isThumb {
NSString* urlString = [NSString stringWithFormat:#"%#/%#upload/%#%#.jpg", kAPIHost, kAPIPath, IdPhoto, (isThumb)?#"-thumb":#""];
return [NSURL URLWithString:urlString];
}
#end
The issue is that the view of your initial view controller has not been added to the window by the time viewDidLoad is called.
Move that call to viewDidAppear:
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (![[API sharedInstance] isAuthorized]) {
[self performSegueWithIdentifier:#"ShowLogin" sender:self];
}
}

Unable to "pass data" from a UITableViewController to a UIViewController

I am in troubles :)
I am unable to acheive my project because i cannot pass the data from my UITableView to a DetailView (UIViewController)
I am a beginner so i certainly do something wrong but i don't know what. I have red several tutorials and it seems to be ok ... but it's not !
Here is the .h of my UITableViewController :
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "XMLParser.h"
#import "ColzaDetailViewController.h"
#interface ColzaViewController : UITableViewController <XMLParserDelegate>
{
XMLParser *parser;
NSDictionary *colzaInfos;
}
#property (nonatomic, retain) NSDictionary *colzaInfos;
#end
I have create an NSDictionary to store the data I need to pass to the detailView (ColzaDetailViewController)
Here is the part of my UITalbeViewController .h wich is interresting for my problem :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ColzaDetailViewController *detailViewController = [[ColzaDetailViewController alloc] initWithNibName:#"ColzaDetail" bundle:[NSBundle mainBundle]];
colzaInfos = [parser.stories objectAtIndex:indexPath.row];
detailViewController._colzaInfos = colzaInfos;
[self.navigationController pushViewController:detailViewController animated:YES];
NSLog(#"TEST MainView : %#", detailViewController._colzaInfos);
detailViewController = nil;
}
I think everything is ok here. I have put a NSLog (TEST MainView) to check if there is something in my NSDictionary _colzaInfos.
So here are my .h and .m of my DetailVieuw (UIVIewController)
.h
#import <UIKit/UIKit.h>
#import "ColzaViewController.h"
#interface ColzaDetailViewController : UIViewController
{
IBOutlet UILabel *colzaSettle;
NSDictionary *_colzaInfos;
}
#property (nonatomic, strong) NSDictionary *_colzaInfos;
#property (nonatomic, retain) IBOutlet UILabel *colzaSettle;
#end
.m
#import "ColzaDetailViewController.h"
#implementation ColzaDetailViewController
#synthesize _colzaInfos, colzaSettle;
- (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
// Implement loadView to create a view hierarchy programmatically, without using a nib.
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
colzaSettle = [_colzaInfos objectForKey:kCloture];
NSLog(#"TEST DetailView : %#", _colzaInfos);
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
As you can see in the viewDidLoad, i have put a second NSLog (TEST DetailView) in order to check one more time if there is something in my Dictionary
And here are the log :
2012-03-14 16:23:54.240 Mobile Settles[7173:f803] TEST DetailView : (null)
2012-03-14 16:23:54.241 Mobile Settles[7173:f803] TEST MainView : {
date = "13/03/2012\n ";
echeance = "Ao\U00fbt 2012\n ";
settle = "453.25\n ";
variation = "5.75";
}
So As you can see the log for DetailView is NULL but in the MainView contains data.
But i need to get those data in the DetailView in order to display them.
The only thing it seem "strange" for me at this step is the _colzaInfos Dictionary is not alloc and init at anytime ... But i have try to allocate it and initialize it in the .m of the detailViewController but my log was at this time
TEST DetailView : {}
Someone can help me to understand what i am doing wrong.
(if you need another part of my code to check something ... feel free to ask.)
Thanks a lot for help
As you told me to do, i have put the line of code at this place, please let me know if i am wrong. And as i told in the comment, When i put a breakpoint directly in this part of code and when i Run the program, the breakpoint stop the process AFTER the NSLog. And if i try to alloc/init it before, i have nothing : TEST detailView : { }.
Sorry but it does not work :(
The code :
#implementation ColzaDetailViewController
#synthesize _colzaInfos, colzaSettle;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
if (! _colzaInfos)
_colzaInfos = [[NSDictionary alloc] init];
}
return self;
}
Add this to your initWithNibName method in ColzaDetailViewController.m.
if (! _colzaInfos) _colzaInfos = [[NSDictionary alloc] init];
It is same issue if you're using an NSArray. You have to initialize the variable at some point for it to be able to hold data. You've only declared it in the .h file.