【问题标题】:how to create array string如何创建数组字符串
【发布时间】:2009-12-02 07:11:46
【问题描述】:

我有包含学生信息的 NSMutableArray,现在我只想提取学生姓名和他们的平均分,所以我做了什么

    NSMutableArray *stuCollection = [[NSMutableArray alloc] initWithCapacity:[students count]];

for (int i = 0; i < [students count]; i++) 
{
    if([students objectAtIndex:i] != NULL)
    {

    NSDictionary *dic = [students objectAtIndex:i];
    NSString *temp = [dic objectForKey:@"name"];

    [stuCollection  addObject:name];

    }   
}


for(int j=0; j< [stuCollection count]; j++)
{
    NSLOG(@"Name %@",[stuCollection objectAtIndex:j]);
}

我第一次可以运行它,但是当我进行自动扫描时,我可以执行第一个、第二个、第三个循环但应用程序终止显示如下,

2009-12-02 14:57:37.908 AppBuzz[13073:207] * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[NSCFArray insertObject:atIndex:]:尝试插入 nil' 2009-12-02 14:57:37.916 AppBuzz[13073:207] 堆栈:( 820145437, 837578260, 819694387, 819694291, 814683071, 814716415, 814716245, 17529, 24097, 814480795, 819893443, 819891231, 858682228, 861592624, 861585968, 8997, 8860 ) 在抛出“NSException”实例后调用终止 程序接收信号:“SIGABRT”。

如何改进

谢谢

【问题讨论】:

    标签: iphone arrays string nsmutablearray


    【解决方案1】:

    你了解断言吗?

    assert(students);
    assert([students count]);
    
    NSMutableArray * stuCollection = [[NSMutableArray alloc] initWithCapacity:[students count]];
    assert(stuCollection);
    
    for (int i = 0; i < [students count]; i++) {
        if ([students objectAtIndex:i] != NULL) {
    
            NSDictionary * dic = [students objectAtIndex:i];
            assert(dic);
    
            NSString * temp = [dic objectForKey:@"name"];
            assert(temp);
    
            assert(name);
    
            [stuCollection addObject:name];
        }
    }
    ...
    

    【讨论】:

      【解决方案2】:

      由于students看起来是一个Cocoa集合,你可以使用如下:

      NSArray *studentNames = [students valueForKey:@"name"];

      请参阅 KVC Set and Array Operators 了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-25
        • 2020-04-16
        • 2012-02-18
        相关资源
        最近更新 更多