kyle-c
11/11/2017 - 4:47 PM

Objective-C memo

Structure

  • You have .h and .m file
  • .h files are "Header" files, where you declare functions and variables
  • .m files are "Implementation" files, where you implement functions
  • You have to import .h files in your .m file
  • @property is the keyword for declaring a variable in a .h
  • A property is public
  • A instance variable is private

Allocation

  • To allocate a new objet, you have to follow this syntax: Person *person1 = [[Person alloc] init];

Pointer

  • You have to add an * when declaring a new variable, just before the name (for all non-number objects) (i.e: NSString *myStr = @"Hello")

Getter

  • You can override the getter of a property in your .m like following: -(type)myproperty{...}
  • _myproperty will be the property value

Setter

  • You can override the setter of a property in your .m like following: -(void)setMyproperty:(type)myproperty{...}
  • myproperty will be the new value
  • _mypropertywill be the old value

String

  • You have to use the @sign before the string (i.e: @"Test")
  • You have to use the format function to construct string with variables (i.e: [NSString stringWithFormat: @"My name is %@!", firstName];)

Number

  • You can use int, float or double but if you need to store numbers in an array you have to use NSNumber (i.e: NSNumber *myNum = [NSNumbre numberWithInt:8];)

Dot VS Brackets

  • Use dot just for properties (when possible)

Boolean

  • Use BOOL type
  • Use YES and NO as value
  • Always use if (myBool) {} instead of if (myBool == YES) {}
  • Always use if (!myBool) {} instead of if (myBool == NO) {}

Methods

  • You can declare a function as static with + attribute instead of -

Arrays

  • Use NSArray for array initialized with data (you can't modify data)
  • Use NSMutableArray for array that should be modified

Atomic vs Nonatomic

  • Atomic is thread safe but slower
  • Nonatomic is not thread safe but fast

Strong vs Weak

  • Strong ensure that the compiler does not destroy the object (until the property receive a nil value)
  • Weak is used for delegates, outlets, subviews, controls... It specifie a reference that is strongly referenced by an object. Once the object is destroyed, the weak property is destroyed as well. It avoid retain cycle (memory leak)

Nullability

  • _Nullable is the equivalent of ? in Swift
  • _Nonnull is the equivalent of ! in Swift

Category and Extension

  • A category in Objective-C allows to add features to a Class
  • An extension allows is like a category but also allows to modify properties of a class