iOS: Creating arrays and dictionaries a bit easier

In other languages, you can often do the following to get or set an item from an array:
array[index] = . . .;
But Objective-C has always required you to use verbose methods such as:page49image38888 page49image39584
[array objectAtIndex:. . .]

Happy days have arrived, for the creators of Objective-C have finally brought us the goodies. From now on, you can simply use [ ] brackets to index arrays, dictionaries, and even your own classes!
MasterViewController.m calls objectAtIndex: in quite a few places, for example in tableView:titleForHeaderInSection:. That method currently looks like this:
page50image7152
page50image7848

page50image8864
page50image9560
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if (sortedByName)
return [sortedSectionNames objectAtIndex:section]; else
return nil;
}
page50image17512
page50image18208

You can now simplify it to the following:

page50image19784
page50image20480
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if (sortedByName)
return sortedSectionNames[section]; else
return nil;
}
page50image28392
page50image29088

That looks a lot more natural, especially if you have programmed in other languages before. (It’s also the syntax C uses for regular C arrays.)
Another example is tableView:numberOfRowsInSection:

page50image31744
page50image32440
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (sortedByName)
page50image36536
page50image37232
page51image2080 page51image2776
{
NSString *sectionName = [sortedSectionNames
objectAtIndex:section]; return [[namesDictionary objectForKey:sectionName]
count];
}
else
{
return [sortedValues count];

}
page51image13320 page51image14016

You can simplify this to:

page51image15536 page51image16232
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (sortedByName) {
NSString *sectionName = sortedSectionNames[section];
return [namesDictionary[sectionName] count]; }
else
{
return [sortedValues count];
} }
page51image27360
iOS: Creating arrays and dictionaries a bit easier iOS: Creating arrays and dictionaries a bit easier Reviewed by Ricardo Castellanos on 16:09 Rating: 5

No hay comentarios:

Con la tecnología de Blogger.