Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing autoreleased variable names?

Tags:

objective-c

I am just curious if reusing a variable assigned to a convenience method is ok.

NSDictionary *address = [NSDictionary dictionaryWithObjectsAndKeys:@"Italy", @"Country", 
address = [NSDictionary dictionaryWithObjectsAndKeys:@"England", @"Country", nil];

or should I just assign a 2nd new variable?

NSDictionary *address = [NSDictionary dictionaryWithObjectsAndKeys:@"Italy", @"Country", 
NSDictionary *address2 = [NSDictionary dictionaryWithObjectsAndKeys:@"England", @"Country", nil];

cheers gary

like image 986
fuzzygoat Avatar asked Apr 26 '26 02:04

fuzzygoat


1 Answers

The first example will make the address pointer point to a different object, so you'll lose your reference to the original dictionary.

Because they're autoreleased, it won't leak memory, but you probably want to be able to access both dictionaries in the future. The first example won't do that for you, and you'll lose the first dictionary.

The second example is much better, it allows you reference both dictionaries independently without stepping on one or the other.

However, if you're looking to merge the two dictionaries, you should create a mutable copy of the first dictionary and then use addEntriesFromDictionary: to merge the two. Don't forget to release/autorelease the mutable copy you create when doing this.

like image 196
Jasarien Avatar answered May 02 '26 11:05

Jasarien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!