Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does @[indexPath] do

I followed a tutorial for using a UITableView. The finished code

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete)
    {
        Message *message = [messageList objectAtIndex:indexPath.row];
        [self.persistencyService deleteMessagesFor:message.peer];
        [messageList removeObject:message];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}

My question is: What does @[indexPath] do? Is it the same as?:

[NSArray arrayWithObject:indexPath]
like image 411
Michael90 Avatar asked Sep 04 '13 14:09

Michael90


2 Answers

Yes it is the same, its just the short notation for defining an array. You can do the same with NSDictionary and NSNumber as well. Here some samples (and some more here):

NSArray *shortNotationArray = @[@"string1", @"string2", @"string3"];

NSDictionary *shortNotationDict = @{@"key1":@"value1", @"key2":@"value2"};

NSNumber *shortNotationNumber = @69;
like image 172
PakitoV Avatar answered Oct 03 '22 17:10

PakitoV


Yes, it is. It's a new feature of modern objective-C.

You can create new arrays with the literal @, like in the example you have. This works well not only for NSArrays, but for NSNumbers and NSDictionaries too, like in:

NSNumber *fortyTwo = @42;   // equivalent to [NSNumber numberWithInt:42]

NSDictionary *dictionary = @{
    @"name" : NSUserName(),
    @"date" : [NSDate date],
    @"processInfo" : [NSProcessInfo processInfo] //dictionary with 3 keys and 3 objects
};

NSArray *array = @[@"a", @"b", @"c"]; //array with 3 objects

It nice for accessing the elements too, like this:

NSString *test = array[0]; //this gives you the string @"a"

NSDate *date = dictionary[@"date"]; //this access the object with the key @"date" in the dictionary

You can have more informations here: http://clang.llvm.org/docs/ObjectiveCLiterals.html

like image 41
Lucas Eduardo Avatar answered Oct 03 '22 16:10

Lucas Eduardo