Search code examples
objective-ccocoansattributedstring

Xcode generating warning when invoking RTFFromRange on NSAttributedString with nil for documentAttributes


Xcode 7 is producing a bunch of warnings for code that looks like this:

NSAttributedString *anEntry = ...
someData = [anEntry RTFFromRange: NSMakeRange(0,[anEntry length]) documentAttributes: nil];

The warning is:

Null argument passed to a callee that requires a non-null argument

The docs from Apple are a bit confusing (it looks to me as though there is an editing error), but passing in nil for the documentAttributes argument appears to be acceptable when there are no document attributes (which there are not in my case).

I am looking for a way to address this warning. I could create an (essentially) empty dictionary to pass in as documentAttributes, but this happens a lot in my code and I would rather not clutter it up with the extra code.

Am I missing the real problem? Are the docs wrong about nil being acceptable and I really should be passing in something for documentAttributes?

Anyone encountered this before and found a solution?

EDIT: Based on the answer below, I ended up going with:

NSAttributedString *anEntry = ...
someData = [anEntry RTFFromRange: NSMakeRange(0,[anEntry length]) documentAttributes: @{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType}];

I believe this is correct and it addresses the warning.


Solution

  • As of Xcode 7, Objective-C lets you specific whether parameters can be nil or not. For the NSAttributedString RTFFromRange:documentAttributes: method, neither parameter is allowed to be nil. So the compiler is now telling you that you can't pass nil to a parameter that isn't allowed to be nil.

    You are correct that the docs for the docAttributes parameter is confusing. It seems it was only partially updated. Try passing an empty dictionary.

    Change the code to be:

    NSAttributedString *anEntry = ...
    someData = [anEntry RTFFromRange: NSMakeRange(0,[anEntry length]) documentAttributes: @{}];
    

    This passes an empty dictionary instead of nil.

    See the NSAttributedString dataFromRange:documentAttributes:error: docs for an example of a nullable parameter (the error parameter can be nil).