Vix Hunk
Vix Hunk

Reputation: 323

Sort NSArray having NSData array

i have this nsarray having images data in it images setting dynamically in array but i want to filter data if there is any nil nsdata i dont want it inside my nsarray how can i sort this array. here is my code.

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];

Upvotes: 0

Views: 203

Answers (2)

rmaddy
rmaddy

Reputation: 318824

I would take a completely different approach. The problem is that arrayWithObjects: stops when it encounters a nil. If, for example, imageData1 is nil, your array will only have one image - imageData.

A better way would be to check each one for nil. Only add the non-nil images.

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];

Upvotes: 3

Shubham Daramwar
Shubham Daramwar

Reputation: 287

You can directly check whether the object at that index is 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];
    }
}

Upvotes: 1

Related Questions