Xcode 7, Obj-C, “Null passed to a callee that requires a non-null argument”

你。 提交于 2019-12-30 01:41:18

问题


In Xcode 7, I'm getting this warning:

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

.. from this nil initialization of a NSMutableArray...

    sectionTitles = [[NSMutableArray alloc] initWithObjects:nil];

I've found that I should be using removeAllObjects instead.

    [sectionTitles removeAllObjects];

However, this doesn't allow me to evaluate a sectionTitles.count == 0. I did try sectionTitles == nil, however unless I use iniWithObjects I can't add objects later on.

I need to set the array to nil or zero, when I refresh my datasource, when there's no records. I don't seem to be able to use addObject to add items unless I've used initWithObjects.


回答1:


Why don't you try:

sectionTitles = [[NSMutableArray alloc] init];

or any of the following:

sectionTitles = [[NSMutableArray alloc] initWithCapacity:sectionTitles.count];
sectionTitles = [NSMutableArray new];
sectionTitles = [NSMutableArray array];
sectionTitles = [NSMutableArray arrayWithCapacity:sectionTitles.count];

maybe some silly ones:

sectionTitles = [NSMutableArray arrayWithArray:@[]];
sectionTitles = [@[] mutableCopy];

There are lots of ways to create empty mutable arrays. Just read the doc.




回答2:


Passing non-null parameters is only partly the answer.

The new Objective-C nullability annotations have huge benefits for code on the Swift side of the fence, but there's a substantial gain here even without writing a line of Swift. Pointers marked as nonnull will now give a hint during autocomplete and yield a warning if sent nil instead of a proper pointer.

Read NSHipster comprehensive article.

In oder to take advantage of the same contract in your own code, use nonnull or nullable:

Obj-C

- (nullable Photo *)photoForLocation:(nonnull Location *)location



回答3:


Got the same error when initializing an NSMutableArray with zeros,

[[NSMutableArray alloc] initWithObjects:0, 0, 0, 0, 0, nil];

Changed it to

[NSMutableArray arrayWithArray:@[@0, @0, @0, @0, @0]];


来源:https://stackoverflow.com/questions/31088137/xcode-7-obj-c-null-passed-to-a-callee-that-requires-a-non-null-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!