gpt4 book ai didi

objective-c - iOS/ManagedObjectContext 中的内存管理

转载 作者:行者123 更新时间:2023-11-28 20:47:20 25 4
gpt4 key购买 nike

看来我不了解 Objective C 中的内存管理...唉。

我有以下代码(请注意,在我的例子中,placemark.thoroughfareplacemark.subThoroughfare 都填充了有效数据,因此 if-条件将为 TRUE

item 绑定(bind)到 ManagedObjectContextitem 中的托管变量(例如 place)具有使用 @dynamic 创建的 setter/getter。因此,声明是

@property (nonatomic, retain) NSString *place;
@dynamic place;

在代码的后面,在 ReverseGeocoderDelegate 中,我访问它:

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {

if (placemark.thoroughfare) {
[item.place release];
item.place = [NSString stringWithFormat:@"%@ ", placemark.thoroughfare];
} else {
[item.place release];
item.place = @"Unknown Place";
}
if (placemark.thoroughfare && placemark.subThoroughfare) {
// *** problem is here ***
[item.place release];
item.place = [NSString stringWithFormat:@"%@ %@", placemark.thoroughfare , placemark.subThoroughfare];
}

如果我不在代码中标记的位置释放 item.place,Instruments 会在那里发现内存泄漏。如果我这样做,程序会在我尝试访问违规方法之外的 item.place 时立即崩溃。

有什么想法吗?

最佳答案

首先,我会这样改变逻辑:

NSString *newPlace = nil;

if (placemark.thoroughfare && placemark.subThoroughfare) {
newPlace = [NSString stringWithFormat:@"%@ %@", placemark.thoroughfare , placemark.subThoroughfare];
}
else {
if (placemark.thoroughfare) {
newPlace = [NSString stringWithFormat:@"%@ ", placemark.thoroughfare];
}
else {
newPlace = @"Unknown Place";
}
}

item.place = newPlace; // Either nil of valid string can be assigned to

许多人并不推荐使用 release 来简单地重新初始化指针。如果是为了节省一些内存,则不必这样做。

您之前的逻辑确实释放了两次。 release 最初所做的只是递减 retainCount。如果它是 0,则对象被释放。对象在其 retainCount 为 0 之前不会被释放。

假设您的 item 具有属性 retain 并且由于 stringWithFormat: 返回 autoreleased 字符串,所以在第二个发布,无论如何您都试图发布将要自动发布的内容。

多次清除对象的最佳方法是简单地为其分配 nil

关于objective-c - iOS/ManagedObjectContext 中的内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4705023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com