【问题标题】:Sort NSArray having NSData array对具有 NSData 数组的 NSArray 进行排序
【发布时间】:2016-08-10 13:21:00
【问题描述】:

我有这个 nsarray,其中包含图像数据图像在数组中动态设置,但如果有任何 nil 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];

【问题讨论】:

  • NSArray 中不能有 nil 对象。例如,如果imageData1nil,则该数组将只包含imageData 而没有其他图像。
  • 所以如果我放一些其他的虚拟图片而不是 nil 那么它会起作用吗?我的意思是如果关于 is image 的声明是 dummy 然后 DONOT add is in nsaray,我该如何应用!

标签: ios objective-c arrays nsarray


【解决方案1】:

我会采取完全不同的方法。问题是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];

【讨论】:

  • 尝试这个但应用程序崩溃并输出“***由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[__NSCFData _isDecompressing]:无法识别的选择器发送到实例0x1567164a0'”
【解决方案2】:

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

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

【讨论】:

  • 感谢回复我实际上想将排序后的数据存储在同一个 self.pageImages 中
  • 我实际上想从我的 nsarray 中排除所有包含 nill 数据或没有图像的图像
  • 是的,这就是我要说的。取 finalArray 并存储在 pageImages 中
  • 在 for 循环之后添加 - pageImages = finalArray ;
  • 我做到了,但仍然没有运气:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 2011-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多