Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Wednesday, December 18, 2013

iOS Create a Class Instance by Name

So, you want to create an object instance from a Class object or NSString, eh?

Reflection, as it is more commonly known in Java parlance, is a super-power that allows you to go from a String name to an actual living, breathing, object instance.

If you saw our previous example, we showed you how to get a Class instance from a String name. Now, we'll take that example a little further and show you how to create an instance from it. Here we go:


  // Get a Class object from a NSString... magic!
  Class dictionaryClass = NSClassFromString(@"NSMutableDictionary");
  
  // Use 'reflection' to create an NSDictionary
  NSMutableDictionary *dict = [[dictionaryClass alloc] init];
  
  [dict setObject:@"Test" forKey:@"TestKey"];
  
  // Yep, its
  NSLog(@"%@", [dict objectForKey:@"TestKey"]);
  
  // >> Test

99.999-proof magic right there.

If you found this helpful, please give us a +1 and we'll stay at the top of your searches when you need help again!




About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates