views:

72

answers:

2

Hi everybody,

i have a problem using dataWithContentsOfURL. I'm loading some images from the internet in a loop. The Problem is: if the image at the URL doesn't exist, dataWithContentsOfURL does NOT return nil as expected. The apple reference says it returns nil if NSData could not be created. Here's the Code:

NSString *TermineImgFileName = nil;
NSString *TermineImgPath = nil;
NSURL *TermineImgURL = nil;
NSData *TermineImg = nil;   
for (deviceTermineHighInt; deviceTermineHighInt <= serverTermineHighInt; deviceTermineHighInt++) {
    TermineImgFileName = [NSString stringWithFormat:@"Termine%i.png", deviceTermineHighInt];
    TermineImgURL = [rootURL URLByAppendingPathComponent:TermineImgFileName];
    TermineImg = [NSData dataWithContentsOfURL:TermineImgURL];
    if (TermineImg != nil) {
        TermineImgPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:TermineImgFileName];
        [TermineImg writeToFile:TermineImgPath atomically:YES];
        updateCount += 1;
        NSLog(@"File %@ saved", TermineImgFileName);
    }
    else {
        NSLog(@"Write Error");
    }               
    TermineImg = nil;
}

Do you know why the method doesn't return nil if the file at the URL doesn't exist?

And a second question: Does it make sense to use the Strings, NSURL and NSData as i did? I thought for memory reasons it would be the best way.

Thank you in advance, Nikos

Edit: The variables for the loop are defined before the code, the loop works fine. Also the variable rootURL is a constant defined in the header. The URL is built fine and it works.

A: 

Testing the code (on a single run ). If the image does not exist I get the Write Error as expected. Whats returned is (NULL). Which I think acts the same in this case, and points to a zero value.

There is a stackoverflow post which tries to explain it Here. are-null-and-nil-equivalent

markhunte
Strange behaviour! In my case in the loop the first image, which is not on the server, is also created but with the Data (Image) of the second file. (When the loop is run two times and the first image exists not, the second exists)I will rethink the routine tomorrow again with fresh brain. :)
leMonch
markhunte: `NULL` and `nil` are equivalent (different purposes, but both a null pointer). An NSNull object is not equivalent to them; `nil` is the absence of an object.
Peter Hosey
A: 

I'd say the question is what the server actually does if you request a non-existing image.
If it gives you a 404, -dataWithContentsOfURL: should return nil - but if it doesn't, a NSData instance with the results will be created which just happens to not contain any useful image data.

Georg Fritzsche
Interesting approach! I will test tomorrow with different servers.
leMonch
You're right! The problem was on server-side. I tried today to open a file News1.png which doesn't exist and the server loaded News2.png instead.Thank you very much!
leMonch