热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何解决此错误“数组元素不能为零”?-Howtoresolvethiserror“Arrayelementcannotbenil”?

Belowcodegenerateserror下面的代码生成错误Arrayelementcannotbenil数组元素不能为零whenIassignth

Below code generates error

下面的代码生成错误

Array element can not be nil

数组元素不能为零

when I assign the value in aryResult[0]

当我在aryResult [0]中分配值时

NSMutableArray *tempResult = [[NSMutableArray alloc] initWithCapacity:2];
switch (habitObj.NoOfTimesPer)
{
    case 1://NO_OF_TIMES_PER_DAY
    {
        tempResult = [self getTotalNoOfDaysOrWeeks_createdDate:habitObj.strCreatedDt totalsOf:@"TOTAL_DAYS"];
    }
        break;
    case 2://NO_OF_TIMES_PER_WEEK
    {
        tempResult = [self getTotalNoOfDaysOrWeeks_createdDate:habitObj.strCreatedDt totalsOf:@"TOTAL_WEEKS"];
    }
        break;
    default:
        break;
}
aryResult[0]    = tempResult[0];
aryResult[3]    = tempResult[1];

The code below does not generate error:

下面的代码不会产生错误:

[tempResult addObject:[NSNumber numberWithInt:0]];
[tempResult addObject:[NSNumber numberWithInt:1]];
aryResult[0]    = tempResult[0];
aryResult[3]    = tempResult[1];

1 个解决方案

#1


0  

Your method

你的方法

[self getTotalNoOfDaysOrWeeks_createdDate:habitObj.strCreatedDt totalsOf:@"TOTAL_DAYS"];

[self getTotalNoOfDaysOrWeeks_createdDate:habitObj.strCreatedDt totalsOf:@“TOTAL_DAYS”];

returns nil, so tempResult becomes nil after assignment inside the switch statement.

返回nil,因此tempResult在switch语句中赋值后变为nil。

Calling tempResult[0] is a shorthand for [tempResult objectAtIndex:0]. And it returns nil, because in Objective-C a method called on nil object always returns nil. Then you try to add nil object to NSMutableArray, which is not allowed, so the app crashes.

调用tempResult [0]是[tempResult objectAtIndex:0]的简写。它返回nil,因为在Objective-C中,一个名为nil对象的方法总是返回nil。然后你尝试将nil对象添加到NSMutableArray,这是不允许的,因此应用程序崩溃。


推荐阅读
author-avatar
活宝贝aaaaaaaaaaaaa
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有