对具有NSData数组的NSArray进行排序

时间:2016-08-10 13:21:01

标签: ios objective-c arrays nsarray

我有这个nsarray有图像数据在它的图像动态设置数组但我想过滤数据,如果有任何nd nsdata我不想在我的nsarray内我怎么能排序这个数组。这是我的代码。

NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"profileImg"];
    NSData* imageData1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"profileImg1"];
    NSData* imageData2 = [[NSUserDefaults standardUserDefaults] objectForKey:@"profileImg2"];
    NSData* imageData3 = [[NSUserDefaults standardUserDefaults] objectForKey:@"profileImg3"];
    NSData* imageData4 = [[NSUserDefaults standardUserDefaults] objectForKey:@"profileImg4"];
    NSData* imageData5 = [[NSUserDefaults standardUserDefaults] objectForKey:@"profileImg5"];




    self.pageImages = [NSArray arrayWithObjects:
                                           [UIImage imageWithData:imageData],
                                           [UIImage imageWithData:imageData1],
                                           [UIImage imageWithData:imageData2],
                                           [UIImage imageWithData:imageData3],
                                           [UIImage imageWithData:imageData4],
                                           [UIImage imageWithData:imageData5],nil];

2 个答案:

答案 0 :(得分:3)

我会采取完全不同的方法。问题是arrayWithObjects:在遇到nil时会停止。例如,如果imageData1nil,则您的数组只会有一个图片 - imageData

更好的方法是检查每个nil。只添加非零图像。

NSArray *keys = @[ @"profileImg", @"profileImg1", @"profileImg2", @"profileImg3", @"profileImg4", @"profileImg5" ];
NSMutableArray *images = [NSMutableArray array];
for (NSString *key in keys) {
    NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (imageData) {
        UIImage *image = [UIImage imageWithData:imageData];
        if (image) {
            [images addObject:image];
        }
    }
}

self.pageImages = [images copy];

答案 1 :(得分:0)

您可以直接检查该索引处的对象是否为零。

NSMutableArray * finalArray = [[NSMutableArray alloc] init];
for (int i = 0; i< pageImages.count; i++) {
    if (pageImages[i]){
        UIImage * temp = [pageImages objectAtIndex:i];
        [finalArray addObject:temp];
    }
}