1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Beginner question for passing in objects

Discussion in 'iPhone/iPad Programming' started by thomasjt, May 1, 2009.

  1. macrumors newbie

    #1
    Hello,

    Apologies for my very beginner question, but I've just been trying to optimise some old code and I'm having some problems.

    My question is: is it possible to initialise new objects inside another object initialisation? For example, I've been doing this:

    Code:
    NSString *bob = @"bob";
    NSURL *jeff = [NSURL urlWithString:@"http://bob.com"];
    NSArray *namesAndSites = [NSArray arrayWithObjects: bob, jeff];
    Is there a way to init objects for the array inside the array's initialisation? For example:

    Code:
    NSArray *namesAndSites = [NSArray arrayWithObjects: [I]NSString mystring = whatever, NSURL urlWithString = whatever];[/I]
    I am just finding it very annoying with NSArrays and NSDictionary's that I can't (or really, don't know how) to set up the array/dict and create the variables for the array/dict inside that declaration.

    I hope this makes sense...any help much apprecaited.
     
  2. macrumors 68040

    #2
    why would you want to do that though? it makes it more difficult to read doesn't it?

    i would stick with the method you already use...

    just my opinion coming from a coding background
     
  3. Moderator

    robbieduncan

    Staff Member

    #3
    1) You should be nil terminating your list in arrayWithObjects: as clearly stated in the documentation.

    2) Yes, of course you can, although you cannot assign the objects to variables at the same time:

    Code:
    NSArray *namesAndSites = [NSArray arrayWithObjects: @"bob", [NSURL urlWithString:@"http://bob.com"], nil];
     
  4. macrumors regular

    #4
    I'm surprised it works without the nil termination, normally the app should crash, shouldn't it?
     
  5. Moderator

    robbieduncan

    Staff Member

    #5
    I'd have thought so. I imagine that it was an example, not actual code copied and pasted from an app, especially with those variable names!
     
  6. macrumors newbie

    #6
    Thank you very much for all your help. I did terminate the arrays with nil, I just keep forgetting to do it in examples :)

    So what do you think the best way is to do it? Set up the strings/urls before and then add them in, or do it all in the initialisation of the array? Is there any sort of best practice idea here?
     
  7. Moderator

    robbieduncan

    Staff Member

    #7
    It's a matter of style but personally I'd say if you are declaring a variable that you will use exactly once to just pass the value to another call (like here) then you don't need that variable. Just do it all in one line.
     

Share This Page