Vix Hunk Vix Hunk - 1 year ago 137
Objective-C Question

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

Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download