Crash with exception attempt to insert nil object

2019-07-27 09:13发布

问题:

I'm using NSDictionary to change the appearance of UIBarButtonItem in the appDelegate file:

UIBarButtonItem *barButtonItemProxy = [UIBarButtonItem appearanceWhenContainedIn:
                                       [UINavigationBar class], [UINavigationController class], nil];

NSDictionary *textAttributes = @{UITextAttributeFont :
                                     [UIFont fontWithName:@"ChocoBold" size:13.0f],
                                 UITextAttributeTextColor : [UIColor whiteColor],
                                 UITextAttributeTextShadowColor : [UIColor blackColor],
                                 UITextAttributeTextShadowOffset : [NSValue valueWithUIOffset:UIOffsetMake(0.0f, -1.0f)]
                                 };
[barButtonItemProxy setTitleTextAttributes:textAttributes forState:UIControlStateNormal];

The app works fine in the simulator but when I run it on a device the app crashes with the following exception:

 [__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]

The crash happens in NSDictionary *textAttributes line.

I don't understand which parameter is nil in that dictionary?

回答1:

NSLog(@"font family %@",[UIFont fontNamesForFamilyName:@"Choco"]);

If choco font family exists in your app than it will log all the available font names. Then copy the exact font name. May be the font name you are using is wrong e.g. its Choco-Bold instead of chocobold etc.

NSMutableDictionary *textAttributes = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       [UIColor whiteColor],UITextAttributeTextColor,
                                       [UIColor blackColor],UITextAttributeTextShadowColor,
                                       [NSValue valueWithUIOffset:UIOffsetMake(0.0f, -1.0f)],UITextAttributeTextShadowOffset,
                                       [UIFont fontWithName:@"Helvetica" size:13.0f],UITextAttributeFont,nil];

Try with the "Helvetica" font if it works then the problem is with your font.