OGeek|极客世界-中国程序员成长平台

标题: iphone - 试图从 iOS 中的另一个类中提取属性 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:51
标题: iphone - 试图从 iOS 中的另一个类中提取属性

我对 iOS 开发完全陌生,所以我可能做错了,但我有一个类用于获取坐标 gps 数据,我希望将其作为一个通用类,我可以在许多应用程序中重用。我的问题是从 gps 获取数据以正确显示在其他应用程序中。

这是我的 GPS 类的头文件:

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface LocationAwareness : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@property(copy) NSString *longitude;
@property(copy) NSString *latitude;

@end

这是实现:

#import "LocationAwareness.h"

@implementation LocationAwareness
@synthesize longitude;
@synthesize latitude;


- (id)init {

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
return self;
}

- (void)locationManagerCLLocationManager *)manager didUpdateToLocationCLLocation   *)newLocation fromLocationCLLocation *)oldLocation {

    // Stops updating location if data has been updated within 10 minutes
    if ( abs([newLocation.timestamp timeIntervalSinceDate: [NSDate date]]) < 600) {

        [locationManager stopUpdatingLocation];
        float latitudedata = newLocation.coordinate.latitude;
        latitude = [NSString stringWithFormat"%f", latitudedata];

        float logitudedata = newLocation.coordinate.longitude;
        longitude = [NSString stringWithFormat"%f", logitudedata];

    }
}

@end

现在我似乎找不到任何地方告诉我如何在另一个项目中获取纬度或经度属性。我导入了 header ,并尝试将 LocationAwareness.latitude 存储到一个我可以使用的变量中,但我存储它的所有内容最终都是空白的。当我开始我的主类并 aloc 初始化一个位置感知对象时,gps 会启动,所以我认为它可以工作,但我似乎对它如何工作以使一切井井有条的了解不够。我已经在互联网上搜索了几个小时。有人知道我做错了什么吗?



Best Answer-推荐答案


嗯,这可能会也可能不会导致问题(很有可能),但一个主要问题是您的 init 方法。

开头应该是:

self = [super init];
if (self) {
    // Do your initializing as you did above.
}
return self;

编辑:
我将您的代码与我的更新一起添加到一个项目中,它运行良好。 为了使用它,您应该执行以下操作:

LocationAwareness *loc = [[LocationAwareness alloc] init];

// Give it some time to start updating the current location and then
// in a different function:
NSLog(@"%@", loc.latitude);

编辑 2
无论您在哪里使用它,您都需要声明一个存储它的属性,以便您可以创建一次并多次引用它。为此,请使用以下代码:

在要使用此对象的对象的标题中,将其与其他属性一起添加:

@property (nonatomic, assign) LocationAwareness *location;

然后,在您的实现文件(.m 文件)的顶部,您应该会看到其他 @synthesize 行,添加这一行:

@synthesize location;

然后,按照上面的示例创建您要使用的实际位置实例:

self.location = [[LocationAwareness alloc] init];

现在给它一些时间来确定您的位置并开始提供更新。然后你可以像这样打印位置:

NSLog(@"%@", self.location.latitude);

关于iphone - 试图从 iOS 中的另一个类中提取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10004150/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4