Во-первых, знаете ли вы, какие хорошие сайты или книги по обучению узнали, как кодировать iOS6?Как вызвать переменную из другого класса
Теперь, имея проблему, у меня есть класс AppDelegate и класс ViewController.
Я использую класс AppDelegate, чтобы найти свое текущее местоположение и сохранить его как NSString.
У меня есть метка в моем классе ViewController, где я хочу отобразить свое местоположение.
В Java я обычно просто сделать что-то вроде этого
label.text = AppDelegate.myLocationString;
Но я довольно новыми для Objective C, и я не знаю, как сделать эквивалент. Честно говоря, я даже не уверен, правильно ли я использую этот язык. Есть ли другой способ приблизиться к этой проблеме в объективном c?
Я попытался найти, как это сделать, но я даже не уверен, что правильно формулирую свои поиски, поэтому не знаю, ищу ли я в правильном направлении.
Любая помощь, которая может быть предложена бы очень признателен
Мой код, как сейчас:
AppDelegate.h
#import <UIKit/UIKit.h>
#import CoreLocation/CoreLocation.h
@class BIDViewController;
@interface BIDAppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) BIDViewController *viewController;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSString *myPosition;
@end
LocationManager класс от AppDelegate.m
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSDate *eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15) {
//if it is within the last 15 seconds, use it. Else do nothing.
if (newLocation.horizontalAccuracy < 35.0) {
//location seems pretty accurate so we will use it
NSLog(@"latitude: %+.6f, longitude: %+.6f\n", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
NSLog(@"Horizontal accuracy: %f", newLocation.horizontalAccuracy);
int latDegrees = newLocation.coordinate.latitude;
int lonDegrees = newLocation.coordinate.longitude;
double latDecimal = fabs(newLocation.coordinate.latitude - latDegrees);
double lonDecimal = fabs(newLocation.coordinate.longitude - lonDegrees);
int latMinutes = latDecimal * 60;
int lonMinutes = lonDecimal * 60;
double latSeconds = ((latDecimal * 3600) - (latMinutes * 60));
double lonSeconds = ((lonDecimal * 3600) - (lonMinutes * 60));
_myPosition = [NSString stringWithFormat:@"Lat: %d, %d, %1.4f, Lon: %d, %d, %1.4f", latDegrees, latMinutes, latSeconds, lonDegrees, lonMinutes, lonSeconds];
}
}
}
ViewController.h
#import <UIKit/UIKit.h>
@interface BIDViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *positionLabel;
@end
ViewController.m
#import "BIDViewController.h"
#import "BIDAppDelegate.h"
@interface BIDViewController()
@end
@implementation BIDViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//I have tried setting the label's text here but to no avail so far, I have been
//able to set it as "blah" with the following line:
//
// positionLabel.text = @"blah";
//
//and I have tried things such as the following to populate the label with the
//myPosition variable:
//
// positionLabel.text = _myPosition;
// or
// positionLabel.text = AppDelegate._myPosition;
}
- (void)viewDidUnload
{
[self setPositionLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
Вы всегда удивительны :) –
@AnoopVaidya Shucks ... – trojanfoe
Я получаю сообщение об ошибке: «Используемый тип« BIDAppDelegate »wh требуется арифметический или указательный тип " для этой строки BIDAppDelegate * appDelegate = (BIDAppDelegate) [[UIApplication sharedApplication] delegate]; – Ian