From BC$ MobileTV Wiki
Jump to: navigation, search

Objective-C and Swift comparison

Mutability vs Immutability

In Swift, constants are constant, variables vary, and by default we are encouraged to favor constants (objects are immutable). In Objective-C mutability is limited by certain classes and property attributes; by default all objects are mutable.

Objective-C classes with limited mutability include all Foundation collections. For example, NSStrings are not mutable; to make a change to a string one must either make a new string or use NSMutableString. The same goes for NSArray and NSMutableArray, NSDictionary and NSMutableDictionary, NSSet and NSMutableSet, and the remaining classes which you can read about here:

Dynamic .vs Static Typing

Swift uses only static typing and method resolution.

With Objective-C using both static or dynamic typing and dynamic method resolution which places more power in the hands of the developer, rather than the hands of the compiler; however this also means more responsibility. You could call a method on an instance of a class, and even if that class doesn't implement that method your code will still compile. You can even change or add method implementations at runtime. We don't recommend making a habit of this just yet.

Atomic .vs. Non-Atomic

What does nonatomic mean? Nonatomic is a property attribute. Properties can be either atomic or nonatomic; this distinction relates to how properties are handled in multithreading. It is beyond the scope of this course to get into the specifics of the difference, but the vast majority of properties you will use will be nonatomic. The default is atomic, so you need to write “nonatomic” almost every time you declare a property.