gpt4 book ai didi

iphone - 如何解决 NSException 格式使用非字符串文字的安全问题

转载 作者:行者123 更新时间:2023-12-03 20:40:32 24 4
gpt4 key购买 nike

我正在使用mailcore2这都是基于 block 的。通常他们定义这样的操作

SomeMailCoreOp *op = [session getOp];
[op start:^(NSError* error, id result) {
if (error) {
// handle error code
}
}];

所以我想做的基本上就是每次遇到错误时抛出一个 NSException ..这样我就可以在代码库的其他地方捕获它..所以我创建了一个类别NSError:

@implementation NSError (Addons)

-(NSString *)description {
return [NSString stringWithFormat:@"%@ - %@",
[self localizedDescription], [self localizedFailureReason]];
}
@end

这就是我通常处理错误的方式:

SomeMailCoreOp *op = [session getOp];
[op start:^(NSError* error, id result) {
if (error) {
[NSException raise:@"failure" format:[error description]];
}
}];

我认为这是有道理的,因为在documentation中对于 NSException,他们得到了 format:

format, A human-readable message string (that is, the exception reason) with conversion specifications for the variable arguments that follow.

但是当我执行上述操作时,我总是收到此编译器警告:

format string is not a string literal (potentially insecure)

我该如何解决这个问题?

最佳答案

format 是一个格式字符串,如 NSLog()[NSString stringWithFormat:] 中所示。对于你的情况

[NSException raise:@"failure" format:@"%@", [error description]];

不会产生警告。看看Apple Docs for formatting string objects了解更多信息。

有关为什么使用非文字字符串作为格式不安全的更多信息,请参阅 Uncontrolled format string在维基百科上

请注意,Apple 不鼓励使用异常进行流量控制:

来自Cocoa Core Competencies :

Although exceptions are commonly used in many programming environments to control programming flow or to signify errors, do not use exceptions in this way in Cocoa and Cocoa Touch applications. Instead, you should use the return value of a method or function to indicate that an error has occurred, and provide information about the problem in an error object.

来自Dealing with Error :

If you’re coming from other platforms and languages, you may be used to working with exceptions for the majority of error handling. When you’re writing code with Objective-C, exceptions are used solely for programmer errors, like out-of-bounds array access or invalid method arguments. These are the problems that you should find and fix during testing before you ship your app.

关于iphone - 如何解决 NSException 格式使用非字符串文字的安全问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18072330/

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