Objective-C for the C# developer

Objective-C for the C# developer
4 years, 11 months ago 0
Posted in: Programming

After developing in C and C++ for over 10 years, being able to develop in C# was like a dream. A lot of the mundane and tedious bits of code that just needed to be written in C++ could be done quickly (if not automatically) in C#. It let me focus on solving problems rather than figuring out how it get something to work. That being said, Objective-C falls somewhere in between, especially with the introduction of automatic reference counting. To me Objective-C feels a lot like the managed C++ and C++/CLI languages, where 90% of the coding is the same and straight forward, but that 10% of syntax differences and nuances are the real frustration points.

So I thought I’ve save myself some trouble (and hair) by tabling out common things that need to be done in Objective-C, but in terms that a C# developer would know. I view this table as a living entity of sorts and will update it with new snippets as I come across them.

Date and Time

Current Date and Time

DateTime now = DateTime.Now;
NSDate * now;
now = [NSDate date];

Formatted Date and Time String

string currentDate = DateTime.Now.ToString("MMMM d, yyyy hh:mm:ssa");
NSDate * now;
NSDateFormatter * dateFormat;
NSString * currentDate;

now = [NSDate date];

dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM d, yyyy hh:mm:ssa"];
currentDate = [dateFormat stringFromDate:now];

String Manipulation

Comparing Strings

string a = "a";
string b = "b";
bool equal = a == b;
NSString * a = @"a";
NSString * b = @"b";
bool equal = [a isEqualToString:b];

Appending Strings

string a = "a";
string b = "b";
string ab = a + b;

NSString * a = @"a";
NSString * b = @"b";

// Must use string formatting to achieve appending.
NSString * ab = [NSString stringWithFormat:@"%@%@", a, b];

String Formatting

string a = "a";
int num = 97;

// Prints out string "a: 97"
string aNum = String.Format("{0}: {1}", a, num);

NSString * a = @"a";
int num = 97;

// Prints out string "a: 97"
NSString * aNum = [NSString stringWithFormat:@"%@: %d", a, num];

Converting a String to an Integer

string a = "97";
int number = Convert.ToInt32(a);
NSString * a = @"97";
int number = [a intValue];
Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *