Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

thomasjt

macrumors newbie
Original poster
Apr 16, 2009
23
0
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.
 
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
 
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];
 
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];

I'm surprised it works without the nil termination, normally the app should crash, shouldn't it?
 
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?
 
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?

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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.