如何在类中存储位置(CLLocationCooperative2D)而不泄漏内存?
我正在创建一个库,其中包含一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CLLocationCooperative2D
是一种非对象类型。它不是从NSObject
继承的,因此不能被retain
ed。因此,像这样声明您的实例变量属性声明如下:
然后您的
setLocation:
方法很简单:这个
setLocation:
方法也是可选的,因为合成的属性将分配给你。但是当分配新位置时,您似乎想做一些其他事情,所以这应该可以让您这样做。CLLocationCoordinate2D
is a non-object type. It does not inherit fromNSObject
so it cannot beretain
ed. So declare your instance variable like soWith the property declaration like:
And then your
setLocation:
method is simply: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.@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