Objective-C tips
This small document gathers useful information to Objective-C developers. It is useful to beginners, but also to advanced users, as it acts as a reference which help prevent mistakes that come from switching too often from one language to another (like me !).
Common mistakes
Here is a list of common mistakes in Objective-C:
- Using C strings instead of Objc strings:
NSLog?("Hello")willSIGTRAPwetherNSLog?(@"Hello")will work. - Using = to compare ObjC? strings:
NSString?is a pointer to a string, use theisEqualToString:if you want things to work well ! - Release autoreleased objects: objects returned by most class method such as
+createFrom...return an autoreleased object, which you should not release - but retain if you need it a longer. More here. - Not releasing an allocated object: when you
allocan Objective-C object, it has a retain count of 1. More here.
Good to know
- The equivalent of a good old Java
isInstanceis as follows:[someObject isKindOfClass:[SomeClass? class]]. This returns either true or false. - When you encounter memory allocations problem, such as double frees, you should use the
malloc_historycommand when your program is running. More here.
GNUstep? specific
- When you are writing a makefile (which can get quite tricky), you can use the "
make messages=yes" option so that the makefile displays what commands it used to make your project. - If you get
no newline at end of filewarnings, then add a newline after each of your header and source file, this is a GCC requirement because some C or Objectice-C parser always expect a newline before the EOF. The Apple version of GCC does not complain about this, though.
Further information
There are many very useful articles on Cocoa Dev Central, especially the basic ones, which help to quickly get in touch with Objective-C and the Foundation framework.
You will also surely find a lot of useful information on the Cocoadev Wiki.
