How to add NSMutableArray as objectAtIndex for NSMutableArray

孤人 提交于 2020-01-14 06:40:10

问题


How to add NSMutableArray as an object(i) for another NSMutableArray

My code is:

yearImages = [[NSMutableArray alloc]init];
tempImages = [[NSMutableArray alloc]init];

for(int i =0; i< [yearImagesName count]; i++)
{
    for(int j=0; j<[totalImagesName count]; j++)
    {
        if ([[totalImagesName objectAtIndex:j] rangeOfString:[yearImagesName objectAtIndex:i]].location != NSNotFound)
        {
            [tempImages addObject:[totalImagesName objectAtIndex:j]];
        }

    }

    [yearImages addObject:tempImages]; 
    [tempImages removeAllObjects];
}

NSLog(@"\n\n  year%@",[yearImages objectAtIndex:0]); // getting null result
  • Here i need to add tempImages as object of (i) for yearImages..

  • I need result as like follows:


[yearImages objectAtIndex:i];// result need as arrayobjects here

回答1:


You are removing the objects from tempImages after you add it, so the result will be an array of empty arrays. You should add a copy of tempImages instead: [yearImages addObject:tempImages.copy] (or a mutableCopy if you require that)




回答2:


Does this even compile? k in [yearImages insertObject:tempImages atIndex:k] is not declared at all.

What error are you getting?

In order to simplify your code, you could get rid of the indices using this code.

yearImages = [[NSMutableArray alloc]init];
tempImages = [[NSMutableArray alloc]init];

for(NSString *yearImageName in yearImagesName)
{
    for(NSString *totalImageName in totalImagesName)
    {
        if ([totalImageName rangeOfString:yearImageName].location != NSNotFound)
        {
            [tempImages addObject:totalImageName];
        }
    }

    [yearImages addObject:tempImages];
    [tempImages removeAllObjects];
}



回答3:


Its very simple.

Replace [yearImages objectAtIndex:i] into [yearImages addObject:tempImages.copy]

Now see full code:

for(int i =0; i< [yearImagesName count]; i++)
{
    for(int j=0; j<[totalImagesName count]; j++)
    {
        if (// Your Conditon)
        {
            [tempImages addObject:[totalImagesName objectAtIndex:j]];
        }

    }

    [yearImages addObject:tempImages.copy]; // each array stored as an object
    [tempImages removeAllObjects];
}
NSLog(@"\n\n  year%@",[yearImages objectAtIndex:0]);


来源:https://stackoverflow.com/questions/20262727/how-to-add-nsmutablearray-as-objectatindex-for-nsmutablearray

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