Imagine I have the following NSDictionary
dict = {
"a" = [
obj1,
obj2,
obj3
],
"b" = [
obj4,
obj5
],
"invalid" = [
obj6,
obj7,
obj8
],
"c" = [
obj9,
obj10,
obj11
]
}
This data is used to populate a TableView
using sections from the following NSArray
:
arr = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];
I have the following method which I use to find an object
- (void)selectRowWithId:(NSNumber *)uid {
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id == %@)", uid];
NSArray *filteredDictArray = [obj filteredArrayUsingPredicate:predicate];
if ([filteredDictArray count] > 0) {
NSIndexPath *targetIndexPath = nil;
//trying to find the NSIndexPath here
[[self tableView] selectRowAtIndexPath:targetIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
[self tableView:[self tableView] didSelectRowAtIndexPath:targetIndexPath];
}
}];
}
Say I have an object set to obj10
.
Based on my NSDictionary
and NSArray
the NSIndexPath
is Section:2 Row:1
How can I get this value if I only know obj10
?
So With a combination of the ideas behind everyone's answers and my own here is the following I used in case it's helpful for someone. BTW: This is for iOS9
- (void)selectRowWithId:(NSNumber *)uid {
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id == %@)", uid];
NSArray *filteredDictArray = [obj filteredArrayUsingPredicate:predicate];
if ([filteredDictArray count] > 0) {
//trying to find the NSIndexPath here
NSIndexPath *targetIndexPath = [NSIndexPath indexPathForRow:[[dict objectForKey:key] indexOfObject:filteredPersonsArray[0]] inSection:[arr indexOfObject:key]];
[[self tableView] selectRowAtIndexPath:targetIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
[self tableView:[self tableView] didSelectRowAtIndexPath:targetIndexPath];
}
}];
}
Your code is a little bit too tricky. Sometimes usual looping is easier.
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL * stop)
{
for( NSInteger index = 0; index < [obj count]; index++ )
{
if ([obj[index] isEqualToString:uid])
{
// thats the index
// Let's have a look-up for the section
NSString *sectionKey = [[key substringToIndex:1] uppercaseString]; //Typo
for( NSInteger section=0; section < [arr count]; section++ )
{
if( [arr[section] isEqualToString:sectionKey] )
{
// That's the section
}
}
}
}
}
Typed in Safari.
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.