Objective-C for PHP Developers: Strings as Variable Names

May 13, 2010   #framework  #objective-c  #php  #tutorial 

After the long introductory post, I decided that it would be more beneficial to look at individual aspects of Objective-C instead of having long posts.

Using strings as variable names

One of the features that I love about PHP and is lacking in many languages is the ability to use a string to represent a variable name. In PHP, the code looks something like this:

<?php
$a = ''hello world!'';
$b = ''a'';
echo $$b; //returns ''hello world!'';

//To set the variable
$$b = ''hello universe!'';

echo $a; //returns ''hello universe!'';

PHP is really robust in this way. You can use strings to represent class names, functions. There are some limitations (usually when dealing with static calls), but it is so powerful that I probably use some form of this code every day.

In Obj-C, there are 2 methods that you can use (a getter method and a setter method). The same code above would look like:

//MyObject.h file

@interface MyObject : NSObject {
	NSString *a;
	NSString *b;
}
@property (nonatomic, retain) NSString *a;
@property (nonatomic, retain) NSString *b;

- (void)myMethod;

@end

//MyObject.m file

#import "MyObject.h"
@implementation MyObject
@synthesize a, b;

- (void)myMethod {
	self.a = @"hello world!";
	self.b = @"a";

	NSLog(@"%@", [self valueForKey:b]); //returns ''hello world!'' to the console;

	[self setValue:@"hello universe!" forKey:b]; //same as self.a = @"hello universe!";
}
@end

These two functions and a few others that you can use when dealing with dictionaries have been quite handy and have been a savior in several instances.