You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于为NSError**类型参数添加nonnull属性的技术问询

Can I add nonnull to a double pointer (like NSError**)?

Great question! Short answer: Yes, you absolutely can add nonnull to a double pointer—but you need to be careful about which level of the pointer you're applying the qualifier to, especially for NSError** parameters.

Let me break this down with your specific scenario:

First, let's recall how nullability qualifiers work with pointers in Objective-C. For a double pointer like NSError**, there are two layers to consider:

  • The outer pointer: This is the variable your caller passes in (the error parameter itself—think of it as a pointer to a pointer).
  • The inner pointer: This is the NSError* that the outer pointer points to (the actual error object reference).

Your goal is to prevent callers from passing nil as the error parameter (to avoid that "Potential null dereference" warning when you try to assign *error = someError). To do that, you want to mark the outer pointer as nonnull, while leaving the inner pointer as nullable (since you won't set an error if the operation succeeds).

Here's how you'd write that in modern Objective-C:

- (BOOL)performTaskWithError:(NSError * _Nullable * _Nonnull)error;

Or using the older double-underscore syntax:

- (BOOL)performTaskWithError:(NSError * __nullable * __nonnull)error;

This tells both the compiler and static analyzer two things:

  1. Callers must pass a valid pointer (not nil) for the error parameter—they can't skip passing it or pass NULL.
  2. The inner NSError* can be nil (which is exactly what happens when your method succeeds and doesn't need to report an error).

This aligns with the spirit of the Creating and Returning NSError Objects guidelines: you're still allowing the method to signal success/failure via the return value, but you're enforcing that callers provide a valid place to receive an error if one occurs—eliminating the null dereference risk entirely.

A quick note: Don't mark the inner NSError* as nonnull unless you guarantee that your method will always return an error (which is almost never the case for methods using the standard "BOOL return + error out" pattern). That would force you to assign an error even when the operation succeeds, which violates common coding practices.

Once you apply this qualifier, the static analyzer should stop complaining about potential null dereferences, since it knows the error parameter itself can't be nil—you can safely dereference it to set an error object when needed.

内容的提问来源于stack exchange,提问作者Kyle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:14:13