Showing posts with label Objective-C. Show all posts
Showing posts with label Objective-C. Show all posts

Monday, January 26, 2009

Objective-C versus C#, part 2: Loading, rotating, and saving an image

 

In this example, I’ll compare Objective-C/Cocoa Touch to C#/.NET in their ability to load an image from a file, rotate it 90 degrees, and then save the modified image.  Both platforms are perfectly capable of performing this task.  One of them, however, sucks orders of magnitude less.  I’ll leave it as an exercise to the reader to decide to which I’m referring.  I’ll list the C# example first this time, since I wouldn’t want to be accused of favoritism.  In fairness, I should point out that for the Objective-C version, I cut some corners.  By using a UIImageView to house the image, I saved many lines of code that would result from applying transforms to the graphics context directly.

C#/.NET

Image myImage = Image.FromFile(@"c:\myImage.png");
myImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
myImage.Save(@"c:\newImage.png");

Objective-C/Cocoa Touch

UIImage* myImage = [UIImage imageNamed:@"myImage.png"];
UIImageView* imageView = [[UIImageView alloc] initWithImage:myImage];
[imageView setTransform:CGAffineTransformMakeRotation(M_PI / 2.0)];

CGSize newImageSize = CGSizeMake(myImage.size.y, myImage.size.x);
UIGraphicsBeginImageContext(newImageSize);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* newImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
UIGraphicsEndImageContext();

[UIImagePNGRepresentation(newImage) writeToFile:@"myNewImage.png" atomically:YES];

[imageView release];
[newImage release];

Sunday, January 18, 2009

Objective-C versus C#, part 1: Searching for a substring within a string

 

I’ve been wanting to create a series of comparisons between the syntax of Objective-C and C#.  I’ve been writing a lot of both these days, so I have a lot of experience with each.  For our first example, let’s say we wanted to check for a substring within a string:

Objective-C

if ([myString rangeOfString:@"mySubstring"].location == NSNotFound)) {
   NSLog(@"mySubstring not found in myString: %@", myString);
}

I don’t know how you could get any more intuitive than that, but just for kicks let’s look at the C# equivalent:

C#

if (!myString.Contains(“mySubstring”))
{
    Console.WriteLine(“mySubstring not found in myString: “ + myString);
}