objective-cnullablenon-nullableobjective-c-nullability

Exactly how to use nonnull in certain cases in Objective C


I have read many posts about nullability but I can't for the life of me make my warnings go away. Here are a couple of examples:

playPause = @[[UIImage imageNamed:@"Play"], [UIImage imageNamed: @"Pause"]];
[imagePropertiesFileHandle writeData:[header dataUsingEncoding:NSUTF8StringEncoding]];

Each of these gets this warning: "implicit conversion from nullable pointer 'NSData * _Nullable' to non-nullable pointer type 'NDSata* _Nonnull'

Surrounding the code with NS_ASSUME_NONNULL_BEGIN/End doesn't work either.

I've tried a wide variety of combinations of (nonnull) __nonnull, etc and can't seem to find the magic location of keywords to make the warning go away.


Solution

  • The problem is that the NSString dataUsingEncoding: method can return nil. But the NSFileHandle writeData: doesn't accept a nil parameter.

    Split this line:

    [imagePropertiesFileHandle writeData:[header dataUsingEncoding:NSUTF8StringEncoding]];
    

    Into these:

    NSData *data = [header dataUsingEncoding:NSUTF8StringEncoding];
    if (data) {
        [imagePropertiesFileHandle writeData:data];
    }