Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
C# to Objective C by example #1
-int main(int argc, const char *argv[] )
// This is the long hand way of doing it.
MyObject *myobj = [MyObject alloc];
[myobj init];
// Bill: Never split the alloc and init calls:
// alloc may return a placeholder that is replaced by -init. Example; NSString never returns a real instance on +alloc
// because it isn't until the -init that it has enough information to know which subclass to use.
MyObject *myobj2 = [[MyObject alloc] init];
// Make sure you release after usage, particularly on the itouch/iphone which has no GC.
// Going into memory management is too big a topic to cover, so it's worth reading up on.
[myobj release];
[myobj2 release];
// You can use [myobj autorelease] which will manage releasing retained objects.
// I've ignored reference counting and retaining though, it fits under memory management which you
// will need to read up on if you don't want to make a leaky app.
// Constructors - Objective-C doesn't have them.
// You can sort of simulate them with initWithName but it won't be the same. As you can see it's a method (which is really
// what constructors are in C# but with special super powers).
// You could use the initializer like so:
// MyClass *myclass = [[MyClass alloc] initWithName: @"hello world"];
-(MyClass*) initWithName : (NSString*) aName
// This also demonstrates the self and super keywords briefly
self = [super init];
// Bill: Note that some will claim that = name is wrong; you shouldn't use accessors in initializer. I don't happen to agree.
if (self) = aName;
return self;
// Abstract class
// There is no built in language keyword for this, however it's easy to implement
// by overriding the default init method, returning null
- (id)init
// You can use NULL or nil
if ([self isMemberOfClass: [AbstractClass class]])
NSLog(@"You can't instantiate an abstract class");
[self release];
return NULL;
if(self = [super init])
// Initialize other stuff
// You would also need to do this for methods if you wanted to simulate abstract methods
[self release];
return NULL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.