gpt4 book ai didi

ios - 重用同一个 NSError 对象会不会有问题?

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

我已将我的实现更改为不再再执行此操作,但我很想知道以下是否会导致问题 - 例如一个包含多个步骤的过程,每个步骤都涉及传递对 NSError 对象的引用。如果您在此过程中的每一步都重复使用此错误对象,该引用是否会以某种方式受到负面影响,可能会导致某种内存管理/取消分配崩溃?

示例(省略了大部分中间代码)

    NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error];

if (!data) {
return error;
}

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if (!responseData) {
return error;
}

NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];

if (!resultDictionary) {
return error;
}

即使错误从未被“使用”两次,这意味着下次将其引用传递给另一个方法时错误将为零(看起来),引用是否可以在沿途的任何步骤中以某种方式受到影响怎么办?

根据 jlehr 的评论进行编辑之前的原始代码:

    NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error];

if (error) {
return;
}

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if (error) {
return;
}

NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];

if (error) {
return;
}

编辑:对于以后来到这里的任何人,jlehr 所指的信息可以在这里找到:

When dealing with errors passed by reference, it’s important to test the return value of the method to see whether an error occurred, as shown above. Don’t just test to see whether the error pointer was set to point to an error.

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ErrorHandling/ErrorHandling.html

最佳答案

根据 Apple 的文档,您永远不应该检查通过引用返回的 NSError 对象。相反,检查 init... 方法或您正在调用的工厂方法的返回值,例如:

NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error];
if (data == nil) {
// Handle failure. It's safe to use the error object here.
}

但是,您的代码似乎没有对 NSError 实例执行任何操作(例如,记录日志或显示警报),因此您只需传递 NULL 相反。

NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL];
if (data == nil) {
// Handle failure.
}

关于ios - 重用同一个 NSError 对象会不会有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25558442/

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