Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 如何在没有内存泄漏的情况下使用+[NSException raise:format:arguments:]?_Objective C_Exception Handling_Nsexception - Fatal编程技术网

Objective c 如何在没有内存泄漏的情况下使用+[NSException raise:format:arguments:]?

Objective c 如何在没有内存泄漏的情况下使用+[NSException raise:format:arguments:]?,objective-c,exception-handling,nsexception,Objective C,Exception Handling,Nsexception,我正在编写一个自定义断言宏,当断言失败时,调用此函数 void _XLCAssertionFailedCritical(NSString *format, ...) { va_list ap; va_start(ap, format); // this suppose to throw exception [NSException raise:NSInternalInconsistencyException format:format arguments:ap]

我正在编写一个自定义断言宏,当断言失败时,调用此函数

void _XLCAssertionFailedCritical(NSString *format, ...)
{
    va_list ap;
    va_start(ap, format);

    // this suppose to throw exception
    [NSException raise:NSInternalInconsistencyException format:format arguments:ap];

    va_end(ap); // <---- this line is unreachable? 
}
但我后来意识到这个函数有内存泄漏。。。瓦乌·恩达普;这是遥不可及的

我可以使用其他方法来创建和抛出异常,但这个方法只是在监听我。似乎不可能在没有内存泄漏的情况下使用它

我知道在正常的控制流中不会发生异常,但即使在异常情况下,我仍然希望编写内存无泄漏问题


此方法意味着是一种方便的方法,因此使用某些格式字符串引发异常可能更简单。但是,以内存泄漏为代价?

我不确定这是否会导致泄漏,特别是如果它是一个断言,这是致命的,但它看起来不太好,不是吗。我建议格式化字符串,然后直接将其传递给[NSException raise:format:]

该问题与+[NSException raise:format:arguments:]无关。使用变量参数列表时,它始终适用。异常安全性和通用C代码不能很好地结合在一起,这是一般问题的一部分。在这种情况下,最好的解决方案是避免抛出va_开始-va_结束间隔。
void _XLCAssertionFailedCritical(NSString *format, ...)
{
    va_list ap;
    va_start(ap, format);
    NSString *message = [[NSString alloc] initWithFormat:format
                                               arguments:ap];
    va_end(ap);

    [NSException raise:NSInternalInconsistencyException
                format:@"%@", message];
}