Jules
Jules

Reputation: 7766

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

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.

Upvotes: 26

Views: 40603

Answers (3)

Scott_Bailey_
Scott_Bailey_

Reputation: 1

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]];

Upvotes: -6

SwiftArchitect
SwiftArchitect

Reputation: 48514

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

Upvotes: 25

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

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.

Upvotes: 20

Related Questions