如何在类中存储位置(CLLocationCooperative2D)而不泄漏内存?

发布于 2024-08-24 12:41:35 字数 503 浏览 4 评论 0原文

我正在创建一个库,其中包含一个 API,用于根据 GPS 收集的某些值设置当前位置。我想将此位置存储在我的类中,然后更改我的库的行为(如果已设置)。

我的想法是:

@interface myLib
{
@property (nonatomic, retain) CLLocationCoordinate2D *location;
}

@implementation myLib
{
@synthesize location = _location;

- (void)setLocation:(CLLocationCoordinate2D *)loc {
location = loc;
}

- (void)someFunc {
 if (location != nil) ...  
}

}

但是,retain 不是 CLLocationCooperative2D 对象的有效属性。

那么,保存 CLLocationCooperative2D 供以后使用而不浪费内存的正确方法是什么?

I am creating a library which contains an API for setting the current location based off some value collected by the GPS. I want to store this location in my class and later, change the behavior of my library if it is set.

What I had in mind was:

@interface myLib
{
@property (nonatomic, retain) CLLocationCoordinate2D *location;
}

@implementation myLib
{
@synthesize location = _location;

- (void)setLocation:(CLLocationCoordinate2D *)loc {
location = loc;
}

- (void)someFunc {
 if (location != nil) ...  
}

}

However, retain isn't a valid property for a CLLocationCoordinate2D object.

So, what is the proper way to save CLLocationCoordinate2D for later use w/o wasting memory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木格 2024-08-31 12:41:35

CLLocationCooperative2D 是一种非对象类型。它不是从 NSObject 继承的,因此不能被 retain ed。因此,像这样声明您的实例变量

CLLocationCoordinate2D location;

属性声明如下:

@property (nonatomic, assign) CLLocationCoordinate2D location;

然后您的 setLocation: 方法很简单:

- (void)setLocation:(CLLocationCoordinate2D)newLocation {
    location = newLocation;
    // other stuff
}

这个 setLocation: 方法也是可选的,因为合成的属性将分配给你。但是当分配新位置时,您似乎想做一些其他事情,所以这应该可以让您这样做。

CLLocationCoordinate2D is a non-object type. It does not inherit from NSObject so it cannot be retained. So declare your instance variable like so

CLLocationCoordinate2D location;

With the property declaration like:

@property (nonatomic, assign) CLLocationCoordinate2D location;

And then your setLocation: method is simply:

- (void)setLocation:(CLLocationCoordinate2D)newLocation {
    location = newLocation;
    // other stuff
}

This setLocation: method is also optional since the synthesized property will assign for you. But you seem to want to do some other stuff when a new location is assigned, so this should let you do that.

卸妝后依然美 2024-08-31 12:41:35

@synthesize 将为您生成 getter 和 setter。

因此这是多余的
- (void)setLocation:(CLLocationCooperative2D *)loc {
位置=地点;

技术上讲是错误的,因为这是“分配”设置器,而不是“保留”设置器。

我猜这就是泄漏发生的地方

@synthesize will generate the getters and setters for you.

Therefore this is redundant
- (void)setLocation:(CLLocationCoordinate2D *)loc {
location = loc;
}

And technically wrong, because that's "assign" setter and not a "retain" setter.

This is where my guess the leak is happening

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文