From IT Skills
Jump to: navigation, search

Objective-C defines a small but powerful set of extensions to the ANSI C programming language... is the native language for Cocoa programming—it’s the language that the frameworks are written in... your code can call functions defined in non-Cocoa programmatic interfaces, such as the BSD library interfaces in /usr/include. You can even mix C++ code with your Cocoa code


delegate in Objective-C is like callback in JS and #Block in Objective-C is like delegate in CSharp

NSNumber is used to wrap scalar values inside objects... known as boxed values... In Objective-C, any character, numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object... Boxed Enums @(enumValue)

Implicit Boolean Conversion can reduce code readability and hide bugs

In the C language, the #include pre-compile directive always causes a file's contents to be inserted.. Objective-C has the #import directive, equivalent except that each file is included only once per compilation unit

nil is literal for objects corresponding to id or declared via @interface... Nil is for type Class... NULL is for arbitrary C pointers... NSNull is often used in Foundation collections since they cannot store nil values

in Swift there’s a strong distinction between optional and non-optional references, e.g. NSView vs. NSView?, while Objective-C represents boths of these two types as NSView * that is brought into Swift as an implicitly unwrapped optional, NSView! ... _Nullable pointer may have a NULL or nil value, while a _Nonnull one should not... typedef types are not assumed to be nonnull, even within audited regions

value classes in Cocoa are NSString, NSDate, and NSNumber... NSValue can hold any of the scalar types such as char, int, float, or double, as well as pointers, structures, and object IDs. It lets you add items of such data types to collections

static, global variables[edit]

static works mostly like in C. 1 It can either initialize a variable only once. 2 Declaring a variable static in a file above @implementationblock will be available for the whole file only.

+ (void)initialize called after first message to object

extern const id List;

Objective-C now supports class properties, which interoperate with Swift type properties. They are declared as @property (class) NSString *someStringProperty;, and are never synthesised.

memory management[edit]

The autorelease schedules a future release call when the current NSAutoreleasePool is drained, typically at the end of an event cycle

literal NSString are constant, and so -retain, -release, and -autorelease messages to them are ignored

For ARC projects I would use strong instead of retain, I would use assign for C primitive properties and weak for weak references to Objective-C objects.

weak is worse that assign in Xcode with old version like 9


Core Foundation facilitates internationalization with Unicode, XML property lists, URL resource access, and preferences.

Opaque types provide better abstraction and more flexibility for how the underlying functionality is implemented.

Because a framework is a bundle, you may access its contents using the NSBundle class or, for procedural code, CFBundle of Core Foundation... You may create your own frameworks for OS X, but third-party frameworks are not allowed on iOS.

all Swift classes are reference types; therefore, the suffix is redundant. The CFTypeRef type completely remaps to the AnyObject type... Core Foundation objects returned from annotated APIs are automatically memory-managed in Swift—you don't need to invoke the CFRetain, CFRelease, or CFAutorelease.. When Swift imports APIs that have not been annotated, the compiler cannot automatically memory-manage the returned Core Foundation objects.

Frameworks offer the following advantages over static-linked libraries and other types of dynamic shared libraries:

  1. Frameworks group related, but separate, resources together. This grouping makes it easier to install, uninstall, and locate those resources.
  2. Frameworks can include a wider variety of resource types than libraries. For example, a framework can include any relevant header files and documentation.
  3. Multiple versions of a framework can be included in the same bundle. This makes it possible to be backward compatible with older programs.
  4. Only one copy of a framework’s read-only resources reside physically in-memory at any given time, regardless of how many processes are using those resources. This sharing of resources reduces the memory footprint of the system and helps improve performance.

Private frameworks are appropriate for code modules you want to use in your own applications but do not want other developers to use. Public frameworks are intended for use by other developers and usually include headers and documentation defining the framework’s public interface.

messages, selectors[edit]

Forwarding... Objective-C permits the sending of a message to an object that may not respond.. object can forward the message to an object that can respond.

overloading is not supported in Objective-C. It is similar to PHP in that sense.

SEL type can be used to hold a reference to the selector

IMP is a C type referring to the implementation of a method, also known as an implementation pointer

Objective-C with ARC warns for use of performSelector:... Objective-C methods have two hidden arguments, self and _cmd that are implicitly added when you call a method.

Swift itself doesn't use selectors... use optional chaining on protocol types or is/as tests instead of respondsToSelector:, and use closures wherever you can instead of performSelector: for better type/memory safety... But there are still a number of important ObjC-based APIs including timers and the target-action pattern. Swift provides the Selector type for working with these. (Swift automatically uses this in place of ObjC's SEL type.)... The Swift function reference you pass to #selector checks existence, membership in a class, and type signature


Structs take up less size because objects have an extra property isa, which holds their class

In most object oriented languages, allocating memory for an object and initializing it is an atomic operation. In Objective-C, these are separate operations. The class methods alloc (and its historic sibling allocWithZone:) makes the Objective-C runtime reserve the required memory and clears it. Except for a few internal values, all properties and variables are set to 0/NO/nil. The object then is already "valid" but we always want to call a method to actually set up the object, which we call an initializer. These serve the same purpose as constructors in other languages. By convention, these methods start with init.

you can instantiate an abstract class in Objective-C (NSString is a prime example)

Categories provide the ability to add some extra functionality to an object without subclassing or changing the actual object.

you can also use categories to split the implementation of a complex class across multiple source code files... Categories are not usually suitable for declaring additional properties.. it’s not possible to declare an additional instance variable in a category... The only way to add a traditional property—backed by a new instance variable—to an existing class is to use a class extension... A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code... class extensions are often referred to as anonymous categories... extensions used to add private methods or properties

All methods are public... Objective-C instance variables are protected by default.

static type-checking comes back; you’ll get an error if you try to call any method that isn’t defined in the specified protocol. One way to avoid the compiler error is to set the custom protocol to adopt the NSObject protocol... The compiler does not automatically synthesize properties declared in adopted protocols.

Objective-C 2.0 provides non-fragile instance variables ... It eliminates the fragile binary interface problem; superclasses can change sizes without affecting binary compatibility. It allows instance variables that provide the backing for properties to be synthesized without them being declared in the class's interface.... fast enumeration for (Person *p in thePeople)... more efficient code than standard enumeration



validation... searches the class of the receiver for a validation method whose name matches the pattern validate<Key>:error:. If you define such a method for a property, the default implementation of validateValue:forKey:error:

neither the key-value coding protocol nor its default implementation define any mechanism to perform validation automatically... Core Data automatically performs validation when the managed object context is saved ... Cocoa bindings allow you to specify that validation should occur automatically... You typically use the validation described here only in Objective-C. In Swift, property validation is more idiomatically handled by relying on compiler support for optionals and strong type checking, while using the built-in willSet and didSet property observers

  1. NSFormatter's are good for default error messages
  2. take into account that value properties are buggy in validators, use reference objects
  3. when using bindings check "Validates Immediately" if you want implement oldie validateValue:forKey:error: :-(; it is buggy with "Discard Changes" button
  4. you should never invoke a validation method within the -set accessor for a property


Apple provides two ways to do multitasking: The Grand Central Dispatch (GCD) and NSOperationQueue frameworks

modern Obj-C[edit]

Adopting Modern Objective-C... designated initializer, an initializer method that is responsible for calling one of its superclass’s initializers and then initializing its own instance variables. Initializers that are not designated initializers are known as convenience initializers. Convenience initializers typically delegate to another initializer—eventually terminating the chain at a designated initializer—rather than performing initialization themselves... inherited initializers initialize all instance variables... subclass does not need to override the convenience initializers... convenience initializer must delegate to another initializer (with [self init...]

In modern Objective C syntax you can get values from NSArray and NSDictionary containers using container subscripting... array[1;]

NSArray, NSDictionary, NSNumber classes) can also be created using literal syntax ... under manually reference-counted memory management, these objects are autoreleased NSArray *myArray = @[ object1, object2, object3 ]... NSDictionary *myDictionary2 = @{ key1: object1, key2: object2 };


retain, release, retainCount, autorelease or dealloc cannot be sent to objects. Instead, the compiler inserts these messages at compile time automatically, including [super dealloc when dealloc is overridden... ARC uses @autoreleasepool... ARC automatically clears (sets to nil) weak-reference local variables, instance variables, and declared properties... variable attribute __weak]


Block objects are a C-level syntactic and runtime feature that allow you to compose function expressions that can be passed as arguments... a block object is sometimes also called a closure or a lambda

Block is like gelegate in C#.

Apple UI components[edit]

responder model is built around three components: event messages, action messages, and the responder chain. NSResponder also plays an important role in the presentation of error information... view > superviews > window > window controller > the application object. Window with no window controllers: view > superviews > window > the application object

window controller[edit]

window controller is usually the owner of the nib file. Regardless of who is the file’s owner, the window controller is responsible for freeing all top-level objects in the nib

NSWindow... beginSheet:completionHandler: Starts a document-modal session and presents sheet.

view controller[edit]

manage the content of a window in a way that is on a par with iOS view controller... view controller participates in the responder chain. You can implement action methods directly in the view controller... view controller is meant to be highly reusable, such as for dynamically representing various objects

  • viewDidLoad
  • viewWillAppear
    sometimes, we create an xib file, which contains some controls, such as UIButton. Before being displayed, this UIButton may be just a nil pointer. So you can set these control properties in viewWillAppear:.


Another View Controller’s Content[edit]

- presentViewController:animator:

- dismissViewController:

- presentViewControllerAsModalWindow:

- presentViewControllerAsSheet:

Document Architecture[edit]

provides support for apps that manage documents, which are containers for user data that can be stored in files locally and in iCloud... Cocoa document architecture provides your app with many built-in features, such as autosaving, asynchronous document reading and writing, file coordination, and multilevel undo support.


sends actions to window.delegate



CALayer and NSView[edit]

In addition to creating a layer-backed view, you can create a layer-hosting view by assigning a layer directly to the view’s layer property. In a layer-hosting view, you are responsible for managing the view’s layer. To create a layer-hosting view, you must set the layer property first and then set this property to YES... do not add subviews to a layer-hosting view... You still use the view for handling mouse and keyboard events, but drawing must be handled by Core Animation.

Xib practices[edit]