Question

I am converting my xcode project to modern objective c. In my AppDelegate, previously, I have this code:

- (void)customizeAppearance
{
    [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:barButtonFont, UITextAttributeFont, nil] forState:UIControlStateNormal];
}

Following, the literal way to create NSDictionary with @{keys : value}, I changed it to:

[[UIBarButtonItem appearance] setTitleTextAttributes:@{UITextAttributeFont: barButtonFont} forState:UIControlStateNormal];

This one change crashes my system. The error output is:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'

Does anyone know why and what I can do to fix it?

I can ignore it but then it would bite me later on as I will forget. I do want to change my entire project to modern objective c and won't have to remember in the future why one code is not 'modern'.

Thanks.

Was it helpful?

Solution

The problem is that barButtonFont is nil, (probably because you don't have a font called Helvetica CE available). This problem is only exposed when you move to the literal syntax, because "Neither keys nor values can have the value nil in containers. If the compiler can prove that a key or value is nil at compile time, then a warning will be emitted. Otherwise, a runtime error will occur."

There is more detail here: http://clang.llvm.org/docs/ObjectiveCLiterals.html

OTHER TIPS

For setting the attributes you need to set it for both states.

Try this snippet of code:

 NSDictionary* textAttributes = [NSDictionary dictionaryWithObject: [UIFont fontWithName:@"Helvetica" size:45.0] forKey: UITextAttributeFont];

[[UIBarButtonItem appearance] setTitleTextAttributes: textAttributes
                                            forState: UIControlStateDisabled];

[[UIBarButtonItem appearance] setTitleTextAttributes: textAttributes
                                            forState: UIControlStateNormal];

Implement this in Appdelegate

For more details you can refer this answer as well.

UIBarButtonItem appearance setTitleTextAttributes does not affects UIControlStateDisabled state

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top