-3
// Directly assigning the value.
NSString *str = [objDictionary objectForKey:@"attributeName"];

// Assigning with convenience method
NSString *str = [NSString stringWithFormat:@"%@", [objDictionary objectForKey:@"attributeName"]];

// Assigning after being owner to that object.
NSString *str = [[NSString alloc] initWithString:@"%@", [objDictionary objectForKey:@"attributeName"]];

In what cases, We need to identify which one needed to be used in code. ??? Any Reference links for difference between the same???

Or can someone answer the question in depth???

Thanks for the help.

viral
  • 4,168
  • 5
  • 43
  • 68

2 Answers2

3
NSString *str = [objDictionary objectForKey:@"attributeName"];

This is the declaration where you want to user local variable with autorelease memory assigned i.e. you don't need to worry about memory allocation/deallocation.

NSString *str = [NSString stringWithFormat:@"%@", [objDictionary objectForKey:@"attributeName"]];

This method is useful when you need to combine different types in single string i.e. integer/float with string for e.g.

NSString *str = [NSString stringWithFormat:@"%@ and %d", [objDictionary objectForKey:@"attributeName"], 5];

This will result in 'your value and 5'

NSString *str = [[NSString alloc] initWithString:@"%@", [objDictionary objectForKey:@"attributeName"]];

This is the assignment where you are allocating memory and you need to have that variable to use some other place so it will be there until and unless you release the memory of that variable. Make sure when you allocate memory you release memory yourself as you are the responsible one.

For further detailed study I recommend you to visit documentation for NSString which will give you idea about available class/instance methods and how to use.

Hiren
  • 12,720
  • 7
  • 52
  • 72
Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
2

Assuming your dictionary contains a string, under ARC, these are all identical. With manual reference counting, the first two are autoreleased and the last one is retained.

For a reference guide, you can't do much better than the NSString class reference.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • I accepted your answer just because the clarification that"under ARC, all of them are identical."... and I am using ARC. Cheers... – viral May 04 '12 at 06:25
  • You asked for depth as well, and the other answer provided that! – jrturton May 04 '12 at 17:18