iphone - iOS - libical/const char * - 内存使用

标签 iphone objective-c ios icalendar libical

我正在使用 libical 库来解析 iCalendar 格式并从中读取我需要的信息。到目前为止它工作得非常好,但是关于 ical 有一件奇怪的事情。 这是我的代码:

icalcomponent *root = icalparser_parse_string([iCalData cStringUsingEncoding:NSUTF8StringEncoding]);

if (root)
{    
    icalcomponent *currentEvent = icalcomponent_get_first_component(root, ICAL_VEVENT_COMPONENT);

    while (currentEvent)
    {    
        while(currentProperty)
        {    
            icalvalue *value = icalproperty_get_value(currentProperty);
            char *icalString = icalvalue_as_ical_string_r(value); //seems to leak
            NSString *currentValueAsString = [NSString stringWithCString:icalString
                                                                encoding:NSUTF8StringEncoding];
            icalvalue_free(value);
            //...
            //import data
            //...
            icalString = nil;
            currentValueAsString = nil;
            icalproperty_free(currentProperty);
            currentProperty = icalcomponent_get_next_property(currentEvent, ICAL_ANY_PROPERTY);
        } //end while
    } //end while
    icalcomponent_free(currentEvent);
}
icalcomponent_free(root);

//...

我确实使用工具来检查我的内存使用情况,并且能够发现这一行似乎泄漏了:

char *icalString = icalvalue_as_ical_string_r(value); //seems to leak

如果我将此行复制并粘贴 5 或 6 次,我的内存使用量将增长大约 400kb,并且再也不会被释放。

icalvalue_as_ical_string_r 方法没有免费方法,因为它返回一个 char *..

有什么解决这个问题的建议吗?我将不胜感激任何帮助!

编辑

看看苹果文档说如下:

To get a C string from a string object, you are recommended to use UTF8String. This returns a const char * using UTF8 string encoding.

const char *cString = [@"Hello, world" UTF8String];

The C string you receive is owned by a temporary object, and will become invalid when automatic deallocation takes place. If you want to get a permanent C string, you must create a buffer and copy the contents of the const char * returned by the method.

但是如果使用 arc,现在如何正确释放一个 char * 字符串呢? 我试图在我的 while 循环之前添加 @autorelease {...} 但没有任何努力。仍在增加内存使用量...

最佳答案

小心声明“没有自由方法...因为它返回一个 char*”;这绝不是您可以假设的事情。

在没有文档的情况下,您可以查看库的源代码以了解它的作用;例如:

http://libical.sourcearchive.com/documentation/0.44-2/icalvalue_8c-source.html

不幸的是,这个函数可以做很多不同的事情。肯定有一些情况,在返回的缓冲区上调用 free() 是正确的,但也许并没有在所有情况下都得到保证。

我认为最好向库的维护者请求适当的释放方法。他们需要收拾自己的烂摊子; icalvalue_as_ical_string_r() 函数在 switch 中至少有十几种情况可能具有不同的释放要求。

关于iphone - iOS - libical/const char * - 内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11505372/

相关文章:

ios - Mapkit - Swift4 - 如何禁用自动缩放

iphone - 如何从 nsarray 中消除空值?

iphone - 属性(property)申报和自动后备存储分配

objective-c - 制作一个 float 只显示小数点前的 x 位

ios - 我想每秒调用 20 次 installTapOnBus :bufferSize:format:block:

iOS Metal API 在体积内绘制 3d 纹理

iphone - 如何清除以前的 ViewController 的内存

iphone - 如何在iPhone上临时保存数据?

ios - 从推送通知启动时启动 viewController 中的所有对象

ios - 如何从 Have 创建 iOS 和 OSX 库并在 native 应用程序中使用它?