How to fix "misuse of 'nonnull'" warnings in Xcode 7.3?
How to fix "misuse of 'nonnull'" warnings in Xcode 7.3?
- Subject: How to fix "misuse of 'nonnull'" warnings in Xcode 7.3?
- From: Jens Alfke <email@hidden>
- Date: Thu, 25 Feb 2016 13:31:45 -0800
As an experiment I tried turning on the new “misuse of ’nonnull'” warning in Xcode 7.3, and got a ton of warnings. They all make sense, but assuming I were going to correct my code, I don’t know the best way go about it. For example, here’s a real warning reported in my project:
[hostArray addObject: url.host]; // Warning!
Here the problem is that NSURL.host returns a nullable NSString, but -[NSArray addObject:]’s parameter is not nullable.
If I know that the URLs I’m dealing with all have hostnames in them, I could just add an “!” after `url.host`. Except I can’t because this is Obj-C, not Swift. What’s the equivalent? Do I have to add a cast?
[hostArray addObject: (NSString* _Nonnull)url.host];
If I don’t want to trust that the URL has a host, I can use `if let` to test it. But again, what’s the Obj-C equivalent? It seems like I’d need
NSString* _Nonnull host = url.host;
if (host)
[hostArray addObject: host];
The Xcode release notes say this warning is on by default in new projects, so people are going to start running into these issues, but I haven’t seen any explanation of how to resolve them. There’s a post on the Swift blog[1] from a year ago, but it doesn’t go into this. It says to consult the Xcode 6.3 release notes[2], but those only say "In Objective-C code, you can now directly express the nullability of pointers in header files, improving interoperability between Swift and Objective-C” and refer (circularly) to the Xcode release notes for details. I wasn’t able to find any info by googling, probably because this warning is so new.
I can imagine writing clever macros to simplify this, something like
#define NOTNULL(X) ((__typeof(X) _Nonnull)(X))
but maybe there’s a better way…
—Jens
[1]: https://developer.apple.com/swift/blog/?id=25
[2]: https://developer.apple.com/library/ios/documentation/DeveloperTools/Conceptual/WhatsNewXcode/Articles/xcode_6_0.html#//apple_ref/doc/uid/TP40014509-SW21
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden