ios Xcode 7,Obj-C,“Null 传递给需要非空参数的被调用者”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31088137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Xcode 7, Obj-C, "Null passed to a callee that requires a non-null argument"
提问by Jules
In Xcode 7, I'm getting this warning:
在 Xcode 7 中,我收到此警告:
Null passed to a callee that requires a non-null argument
.. from this nil initialization of a NSMutableArray...
.. 从 NSMutableArray 的 nil 初始化...
sectionTitles = [[NSMutableArray alloc] initWithObjects:nil];
I've found that I should be using removeAllObjectsinstead.
我发现我应该使用它removeAllObjects。
[sectionTitles removeAllObjects];
However, this doesn't allow me to evaluate a sectionTitles.count == 0. I did try sectionTitles == nil, however unless I use iniWithObjectsI can't add objects later on.
但是,这不允许我评估sectionTitles.count == 0. 我确实尝试过sectionTitles == nil,但是除非我使用,否则我iniWithObjects以后无法添加对象。
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 addObjectto add items unless I've used initWithObjects.
当我刷新数据源时,当没有记录时,我需要将数组设置为 nil 或零。我似乎无法addObject用来添加项目,除非我使用过initWithObjects.
采纳答案by Jeffery Thomas
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.
有很多方法可以创建空的可变数组。只需阅读文档。
回答by SwiftArchitect
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
nonnullwill now give a hint during autocomplete and yield a warning if sent nil instead of a proper pointer.
新的 Objective-C 可空性注释对 Swift 一侧的代码有巨大的好处,但即使不编写一行 Swift 代码,这里也有很大的收获。标记为的指针
nonnull现在将在自动完成期间给出提示,如果发送 nil 而不是正确的指针,则会产生警告。
Read NSHipster comprehensive article.
阅读 NSHipster综合文章。
In oder to take advantage of the same contract in your own code, use nonnullor nullable:
为了在您自己的代码中利用相同的合同,请使用nonnull或nullable:
Obj-C
对象-C
- (nullable Photo *)photoForLocation:(nonnull Location *)location
回答by Scott_Bailey_
Got the same error when initializing an NSMutableArray with zeros,
用零初始化 NSMutableArray 时出现相同的错误,
[[NSMutableArray alloc] initWithObjects:0, 0, 0, 0, 0, nil];
Changed it to
改成
[NSMutableArray arrayWithArray:@[@0, @0, @0, @0, @0]];

