Register FAQ / Rules Forum Spy Search Today's Posts Mark Forums Read
Go Back   MacRumors Forums > Apple Systems and Services > Programming > iPhone/iPad Programming

Reply
 
Thread Tools Search this Thread Display Modes
Old Dec 16, 2008, 02:22 PM   #1
yrvaken2
macrumors newbie
 
Join Date: Sep 2008
When to allocate?

Can someone please explain the diffrence of the following and when to use what..?

Code:
 NSString *string = [[NSString alloc] initWithFormat:@"hello"];
and

Code:
 NSString *string = @"hello";
I am struggling a bit to get the hang of this memory efficient programing with releasing objects and stuff.
yrvaken2 is offline   0 Reply With Quote
Old Dec 16, 2008, 04:20 PM   #2
xsmasher
macrumors regular
 
Join Date: Jul 2008
Code:
 NSString *string = [[NSString alloc] initWithFormat:@"hello"];
//vs.
NSString *string = @"hello";
They differ in terms of memory management and flexibility. The second method, @"hello" , is a literal string - you don't need to retain or release it. It will always be around. Handy for creating constants. Even if you use this line in a loop, you are NOT creating a new object every time. There's only one @"hello" .

The first one - the alloc/init - creates a new NSString object for you, which you manage (retain/release) as appropriate. Also, the init method you chose, initWithFormat, can take a format string a list of variables - so if you need to combine a list of variables into a string, you can use:
Code:
string = [[NSString alloc] initWithFormat:@"I lost my %@ in %@", bodyPart, city];
You can't do that with the @ method - literal strings are defined when the program is compiled, not when it's running.

I'd use the @"Hello" wherever I have a string that will always be the same every time I run my program, and the longer form whenever I need to construct a string that will be different every time I run my program.

Last edited by xsmasher; Dec 16, 2008 at 04:22 PM. Reason: reduce size of quote
xsmasher is offline   0 Reply With Quote

Reply
MacRumors Forums > Apple Systems and Services > Programming > iPhone/iPad Programming

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Similar Threads
thread Thread Starter Forum Replies Last Post
How much space should I allocate to Boot Camp? Drewbonics Windows, Linux & Others on the Mac 2 Mar 14, 2014 11:47 PM
Allocate Storage and clean it... dirtnnasty OS X Mavericks (10.9) 9 Dec 29, 2013 08:46 AM
iTunes cannot allocate resources Danomac Mac Applications and Mac App Store 0 Oct 27, 2013 08:49 AM
How much memory should I allocate for Windows 7? anewfoundsin Windows, Linux & Others on the Mac 2 Mar 16, 2013 03:21 PM
How much free space to allocate in external HDD? dcslacker Digital Video 2 Aug 5, 2012 04:21 AM

Forum Jump

All times are GMT -5. The time now is 07:28 AM.

Mac Rumors | Mac | iPhone | iPhone Game Reviews | iPhone Apps

Mobile Version | Fixed | Fluid | Fluid HD
Copyright 2002-2013, MacRumors.com, LLC