Note that there are some explanatory texts on larger screens.

plurals
  1. POObj-C easy method to convert from NSObject with properties to NSDictionary?
    primarykey
    data
    text
    <p>I ran across something that I eventually figured out, but think that there's probably a much more efficient way to accomplish it.</p> <p>I had an object (an NSObject which adopted the MKAnnotation protocol) that had a number of properties (title, subtitle,latitude,longitude, info, etc.). I needed to be able to pass this object to another object, which wanted to extract info from it using objectForKey methods, as an NSDictionary (because that's what it was getting from another view controller). </p> <p>What I ended up doing was create a new NSMutableDictionary and use setObject: forKey on it to transfer each piece of vital info, and then I just passed on the newly created dictionary.</p> <p>Was there an <strong>easier</strong> way to do this?</p> <p>Here's the relevant code:</p> <pre><code>// 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; } } </code></pre> <p>Thanks in advance for your collective wisdom.</p> <hr> <h1>Here's what I came up with, thanks to the folks, below...</h1> <pre><code>- (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; } </code></pre> <h2> }</h2> <h1>And a even simpler fix, as seen below...</h1> <p>Using valueForKey instead of object for key to retrieve the information.</p> <hr>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload