What is @[] and @{} in Objective-C? [duplicate]
Asked Answered
C

3

6

Possible Duplicate:
What are the details of “Objective-C Literals” mentioned in the Xcode 4.4 release notes?

I've got question about @[] and @{}.

Some code taken from internet:

self.searches = [@[] mutableCopy]; 
self.searchResults = [@{} mutableCopy]; 
  1. Is @[] equal to [NSMutableDictionary dictionary]?
  2. Is @{} equal to [NSMutableArray array]?
Coacervate answered 28/11, 2012 at 14:9 Comment(0)
T
10
  1. No. @[] is equal to [NSArray array] or [[NSArray alloc] init].
  2. No. @{} is equal to [NSDictionary dictionary] or [[NSDictionary alloc] init].

(depending on the context and whether you use Automatic Reference Counting (ARC) or not)

That's why you see things like [@[] mutableCopy] sometimes. This will create an empty immutable array and create a mutable copy of it.

The result is the same as using [NSMutableDictionary dictionary] or [[NSMutableDictionary alloc] init].

Throes answered 28/11, 2012 at 14:12 Comment(2)
yeah ... it's creating an autoreleased object so the answer is only correct when using arc.Aneurysm
I was assuming anyone starting with Objective-C at this time would use ARC, but good point.Throes
A
1

@{} is equal to [NSDictionary dictionary]

@[] is equal to [NSArray array]

so [@[] mutableCopy] creates an empty immutable object and then it makes a mutablecopy of it. I don't think you can do it less efficient.

Aneurysm answered 28/11, 2012 at 14:12 Comment(2)
yeah .. i copied it from the question ;)Aneurysm
There was a post somewhere about the performance of mutableCopy vs simple alloc/init, but I can't find it...Throes
S
0

First one @[] is a shorthand to create an Array, for example the following array of two elements:

NSArray *array = @[ @"First", @"Second"];

Second one @{} creates a dictionary, for example:

NSDictionary *dictionary = @{
    @"first" : someValue,
    @"second" : someValue,
};
Strepphon answered 28/11, 2012 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.