简体   繁体   中英

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]

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM