Я столкнулся с чем-то, что в конце концов понял, но думаю, что, возможно, гораздо более эффективный способ выполнить его.
У меня был объект (NSObject, который принял протокол MKAnnation), который обладал рядом свойств (название, субтитры, широта, долгота, информация и т.д.). Мне нужно было передать этот объект другому объекту, который хотел извлечь информацию из него с помощью методов objectForKey, как NSDictionary (потому что это то, что он получал с другого контроллера представления).
В результате я создал новый NSMutableDictionary и использовал setObject: forKey для передачи каждой части жизненно важной информации, а затем просто передал только что созданный словарь.
Был ли способ проще сделать это?
Вот соответствующий код:
// sender contains a custom map annotation that has extra properties...
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetailFromMap"])
{
DetailViewController *dest =[segue destinationViewController];
//make a dictionary from annotaion to pass info
NSMutableDictionary *myValues =[[NSMutableDictionary alloc] init];
//fill with the relevant info
[myValues setObject:[sender title] forKey:@"title"] ;
[myValues setObject:[sender subtitle] forKey:@"subtitle"];
[myValues setObject:[sender info] forKey:@"info"];
[myValues setObject:[sender pic] forKey:@"pic"];
[myValues setObject:[sender latitude] forKey:@"latitude"];
[myValues setObject:[sender longitude] forKey:@"longitude"];
//pass values
dest.curLoc = myValues;
}
}
Спасибо за вашу коллективную мудрость.
Вот что я придумал, благодаря людям, ниже...
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetailFromMap"])
{
DetailViewController *dest =[segue destinationViewController];
NSArray *myKeys = [NSArray arrayWithObjects:
@"title",@"subtitle",@"info",@"pic",@"latitude",@"longitude", nil];
//make a dictionary from annotaion to pass info
NSDictionary *myValues =[sender dictionaryWithValuesForKeys:myKeys];
//pass values
dest.curLoc = myValues;
}
}
И еще более простое исправление, как показано ниже...
Использование valueForKey вместо объекта для ключа для получения информации.