Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Nullability: Qualifying Constant Strings

I have gotten into a pretty good habit of declaring and using constant strings for things like NSNotification names. I declare them like so:

extern NSString * const ABCAwesomeThingHappenedNotification;

With the introduction of Xcode 6.3 and Swift 1.2, I'm going back and auditing Objective-C classes that interop with Swift using the new nonnull, nullable, and null_unspecified qualifiers.

When adding the qualifiers to a header that also has externally visible static strings, I receive the following warning:

warning: pointer is missing a nullability type specifier (__nonnull or __nullable)

Hmm. That's confusing / interesting. Can someone explain the reasoning behind this message? When using ABCAwesomeThingHappenedNotification in Swift, it never suggests that it's an optional String or implicitly unwrapped String.

like image 652
edelaney05 Avatar asked Apr 14 '15 16:04

edelaney05


People also ask

What does nullable mean in Objective-C?

nonnull : the value won't be nil. It bridges to a Swift regular reference. nullable : the value can be nil. It bridges to a Swift optional. null_resettable : the value can never be nil when read, but you can set it to nil to reset it.

How many annotations are there in Objective-C?

There are two annotations we can apply to our Objective-C code to improve this situation: Marking types as nonnull imports them as non-optional in Swift. Marking types as nullable imports them as optional in Swift.

What is ID in Obj C?

id is the generic object pointer, an Objective-C type representing "any object". An instance of any Objective-C class can be stored in an id variable.


2 Answers

I agree that having this specifier shouldn't be required but here is syntax

extern NSString * const MyConstant;

extern NSString * __nonnull  const MyConstant;
like image 166
Josip B. Avatar answered Oct 20 '22 13:10

Josip B.


In your implementation, you could define:

NSString * const ABCAwesomeThingHappenedNotification = @"ABCAwesomeThingHappenedNotification";

in which case the pointer is clearly nonnull. However, this is also valid:

NSString * const ABCAwesomeThingHappenedNotification = nil;

which must be considered nullable because the pointer is always a null pointer.

(The explicit initialisation to nil is redundant since this happens implicitly if no initial value is provided, but clarifies this example.)

like image 7
Douglas Hill Avatar answered Oct 20 '22 13:10

Douglas Hill