Changing return value of objectForKey: in case object is not avaible

Discussion in 'Mac Programming' started by lopoz, Mar 29, 2010.

  1. lopoz macrumors regular

    May 10, 2005
    I'm writing a basic image viewer with image metadata support, but I'm having a little trouble when specific metadata can't be found.

    I've extracted the metadata from the image and now I'm creating an array to hold the specific data. BUT, when some data isn't available, the return value will be nil, thus terminating my array, which gives problems for me later on.

    How can I make the return value an empty string? (e.g. @"")

    CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef) url, NULL);
    NSDictionary *metadata = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    metadataList = [NSArray arrayWithObjects:
    					[NSString stringWithFormat:@"%@ x %@", [metadata objectForKey:(id)kCGImagePropertyPixelWidth],[metadata objectForKey:(id)kCGImagePropertyPixelHeight]],
    					[metadata objectForKey:(id)kCGImagePropertyProfileName], etc.etc..
    If any more info is needed, please let me know..

    Thanks in advance!
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    [metadata objectForKey:(id)kCGImagePropertyPixelWidth]?[metadata objectForKey:(id)kCGImagePropertyPixelWidth]:@""
    In the line where you're building up the array, you could do this for each property.

    Or you could create a NSMutableDictionary instead, loop through the keys you want to use in building your new array, and if nil is returned, alter the value to @"".

    There are many other permutations, but hopefully that gives you some ideas.

  3. lopoz thread starter macrumors regular

    May 10, 2005
    Thanks! The question mark approach is working quite nicely! Could you please explain what this does? Or point me to some book/documentation where I could have found this?
  4. splitpea macrumors 6502a

    Oct 21, 2009
    Among the starlings
    It's called a ternary operator. It's basically an inline if/else statement:

    myvar = (a < b) ? c : d;
    is the same as:

    if ( a < b ) {
        myvar = c;
    else {
        myvar = d;
  5. gnasher729 macrumors P6


    Nov 25, 2005
    What about any book that explains programming in C / C++ or Java? It is just the ?: operator, nothing more. For an (almost) definitive source on C programming, type "n1124.pdf" into Google. And remember that Objective C is a superset of C.
  6. lopoz thread starter macrumors regular

    May 10, 2005
    Thanks for that. Could've done without the condescending tone, but whatever..

    @splitpea: Thanks for the info!

Share This Page