1. "new" to create an object if no arguments are needed for initialization.
e.g. XYZObject *object = [XYZObject new];
2. Literals offers a concise object-creation syntax.
NSString *someString = @"Hello, World !";
3. We can create NSNumber using boxed expression, like:
NSNumber *myInt = @(80/12);
4. The "id" type defines a generic object pointer. (object c is a dynamic language! this is just like "var" keyword in C#)
id someObject = @"Hello, World!";
5. Use "isEqual" to test whether two objects represent the same data, available from NSObject.
if([firstObject isEqual:secondObject]) ...
6. "compare" method is provided by basic Foundation types such as NSNumber, NSString and NSDate.
if( [someDate compare:anotherDate] == NSOrderedAscending) ...
7. It's perfectly acceptable in Object-C to send a message to nil, it's just ignored and return nil for object return type, 0 for numeric types and NO for BOOL types.
8. If you want to make sure an object is not null, use this syntax:
if (somePerson) ... directly, as convenient as Javascript.
9. It's important to avoid strong reference cycles.
10. Accessor methods are created by compiler:
NSString *firstName = [somePerson firstName];
[somePerson setFirstName:@"John"];
11. The method used to set the value (the setter method) starts with the word "set" and then uses the capitalized property name.
12. "readonly" attribute can be added to a property declaration to specify that it should be readonly, don't want it to be changed via setter method.
@property (readonly) NSString *fullname;
13. Custom name can be specified using attribute on the property:
@property (getter=isFinished) BOOL finished;
14. Simply include the multiple attributes on property as a comma-separated list, like this:
@property (readonly, getter=isFinished) BOOL finished;
15. Dot syntax is a concise alternative to accessor method calls
NSString *firstName = someperson.firstName;
somePerson.firstName = @"johnny";
16. Should use accessor method or dot syntax for property access even if you're accessing an object's properties from within its own implementation, in such case, should use "self":
-(void) someMethod {
NSString *myString = @"An interesting string";
self.someString = myString;
//or
[self setSomeString:myString];
}
except when writing initialization, deallocation or custom accessor methods.
17. There's a default instance variable created by compiler called _propertyName, we can direct the compiler to synthesize the variable using the following syntax:
@implementation YourClass
@synthesize propertyName = instanceVariableName;
...
@end
18. If using @synthesize without specifying an instance variable name, like this:
@synthesize firstName;
the instance variable name will bear the same name as the property. (without underscore as prefix)
19. It's best practice to use a property on an object any time you need to keep track of a value or another object.
20. If you need to define your own instance variables without declaring a property, add them inside braces at the top of the class interface or implementation, like this:
@interface SomeClass: NSObject {
NSString *_myNonPropertyInstanceVariable;
}
or
@implementation SomeClass {
NSString *_anotherCustomInstanceVariable;
}
21. Should always access the instance variables directly from within the initialization methods, like:
- (id) init {
self = [super init];
if (self) {
//initialize instance variables here.
}
return self;
}
22. An init method should assign self to the result of calling the superclass's initialization method before doing
its own initialization. A superclass may fail to initialize the object correctly and return nil. so you should
always check to make sure self is not nil before performing your own initialization.
23. Should decide which method is the designated initializaer. This is often the method that offers the most options
for initialization (such as the method with the most arguments)
24. Should call the superclass's designated initializer (in place of [super init];) before doing any of your own initialization.
25. You can implement custom accessor methods which is not backed by their own instance variables. like:
@property (readonly) NSString *fullname;
- (NSString *)fullName {
return [NSString stringWithFormat: @"%@ %@", self.firstName, self.lastName];
}
26. If need to write a custom accessor method for a property that uses an instance variable, must access the vairable directly from within the method.
like this "lazy initialize method":
- (XYZObject *)someImportantObject {
if(!_someImportantObject) {
_someImportantObject = [[XYZObject alloc] init];
}
return _someImportantObject;
}
27. The compiler will not synthesize an instance variable automatically if both getter and setter for a readwrite property or a getter for a readonly
property are implemented by you.
28. Properties are atomic by default, the synthesized accessors ensure that a value is always fully retrieved by the getter method or fully set
via the setter method.
29. It's not possible to combine a synthesized accessor with an accessor method that you implement yourself, for example, to provide a custom setter
for an atomic, readwrite property but leave the compiler to synthesize the getter.
30. If property has a "nonatomic" attribute, it's not thread safe, but it's faster to access a nonatomic property, and it's fine to combine a
synthesized setter, for example, with your own getter implementation.
31. Property atomicity is not synonymous with an object's thread safety, thing is more complicated when properties need cooperation.
32. When one object relies on other objects and effectively taking ownership of those other objects, the first object is said to have strong references
to the other objects. an object is kept alive as long as it has at least one strong reference to it from another object.
33. If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from
outside of the group, we should avoid the strong reference cycles.
34. One way to break the strong reference cycle is to subsitute one of the strong references for a weak reference.A week reference does not
imply ownership or responsibility between two objects, and does not keep an object alive.
35. To declare a weak reference, add an attribute of (weak) to the property, like this:
@property (weak) id delegate;
36. If you don't want a variable to maintain a strong reference (which is default behaviour), you can declare it as __weak, like this:
NSObject * __weka weakVariable;
37. Weak variables can be a source of confusion, particularly in code like this:
NSObject * __weak someObject = [[NSObject alloc] init];
in this example, the newly allocated object has no strong reference to it, so it is immediately deallocated and someObject is set to nil.
38. It's important to consider the implications of a method that needs to access a weak property several times, like this:
- (void) someMethod {
[self.weakProperty doSomething];
...
[self.weakProperty doSomethingElse];
}
in this case, we should cache the weak property in a strong variable to ensure it is kept in memory as long as you need to use it.
- (void) someMethod {
NSObject *cachedObject = self.weakProperty;
[cachedObject doSomething];
[cachedObject doSomethingElse];
}
39. It's important to keep in mind if you need to make sure a weak property is not nil before using it, it's not enough just to test it, like this:
if (self.someWeakProperty) {
[someObject doSomethingImportantWith:self.someWeakProperty];
}
because in a multi-threaded application, the property may be deallocated between the test and the method call, rendering the test useless.
should to declare a strong local variable to cache the value instead, like this:
NSObject *cachedObject = self.someWeakProperty; //lock it
if (cachedObject) {
[someObject doSomethingImportantWith:cachedObject];
}
cachedObject = nil;
40. There are some classes in Cocoa and Cocoa Touch that don't yet support weak references, should use unsafe reference instead, like this
@property (unsafe_unretained) NSObject *unsafeProperty;
for variables, need to use __unsafe_unretained:
NSObject * __unsafe_unretained unsafeReference;
why it's call unsafe is because it won't be set to nil if the destination object is deallocated, so it's dangling.
41. The "copy" attribute. used for object to keep its own copy of any objects that are set for its properties.
example:
@interface XYZBadgeView: NSView
@property NSString *firstName;
@property NSString *lastName;
@end
Two NSString properties are declaredd, which both maintain implicit strong references to their objects.
When another object create a string to set as one of the badge view's properties, like this:
NSMutableString *nameString = [NSMutableString stringWithString:"John"];
self.badgeView.firstName = nameString;
then..
[nameString appendString:@"ny"];
the firstName property of badgeView is now "johnny" because the mutable string was changed.
to avoid such case, add (copy) attribute to the properties, like this:
@interface XYZBadgeView: NSView
@property (copy) NSString *firstName;
@property (copy) NSString *lastName;
@end
42. Any object that wish to set for a copy property must conform to the NSCopying protocol.
43. If need to set a copy property's instance variable directly, for example in an initializer method,
don't forget to set a copy of the original object:
...
self = [super init];
if (self) {
_instanceVariableForCopyProperty = [aString copy];
}
return self;
...
44. Categories add methods to existing classes:
@interface ClassName (CategoryName)
@end
45. At runtime, there's no difference between a method added by a category and one that is implemented by the original class.
46. A category is usually declared in a separated header file and implemented in a separate source code file.
47. As well as just adding methods to existing classes, you can also use categories to split the implementation of a complex class
across multiple source code files.
48. Categories are not usually suitable for declaring additional properties. it's not possible to declare an additional instance variable in
a category.
49. In order to avoid undefined behavior, it's best practice to add a prefix to method names in cateogories on framework classes.
50. Class extensions extend the internal implementation.
The methods declared by a class extension are implemented in the @implementation block for the original class.
51. The syntax to declare a class extension is similar to category:
@interface ClassName ()
@end
that's why it's also called "anonymous categories"
52. Unlike regular categories, a class extension can add its own properties and instance variables to a class.
53. Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation
of the class itself. for example, to define a property as readonly in the interface, but as readwrite in a class extension declared above
the implementation, in order that the internal methods of the class can change the property value directly (in implementation file!)
example:
@interface XYZPerson: NSObject
...
@property (readonly) NSString *uniqueIdentifier;
- (void) assignUniqueIdentifier;
@end
this means it's not possible to change the property from other object directly through the property itself.
in order for the XYZPersion class to be able to change the property internally, it make sense to redeclare it in a class extension:
@interface XYZPerson ()
@property (readwrite) NSString *uniqueIdentifier;
@end
@implementation XYZPerson
...
@end
this means that the compiler will now also synthesize a setter method, so any method inside the XYZPerson implementation will be able
to set the property directly using either the setter or dot syntax.
and because it's defined in implementation file, it means it's private.
54. It's common to have two header files for a class, for example,
XYZPerson.h and XYZPersonPrivate.h, when you release the framework, only the public XYZPerson.h header file is released.
55. Other options for class customization:
(1) leverage inheritance and leave the decisions in methods specifically designed to be overridden by subclasses.
(2) use a delegate object, any decision that might limit resusablity can be delegated to another object, which is left to make those
decisions at runtime.
(3) interact directly with the object-c runtime, such as adding "associative references" to an object.
56. Protocol, is used to declare methods and properties that are independent of any specific class.
@protocol ProtocolName
//list of methods and properties
@end
Protocols can inlcude declarations for both instance methods and class methods, as well as properties.
57. Delegate and data source properties are usually marked as weak for object graph management reasons.
58. Protocols can have optional methods
@protocol DataSource
- (NSUInteger)numberOfSegments;
...
@optional
- (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
@required
- ...
@end
59. Check the optional methods are implemented at runtime:
if( [self.dataSource respondsToSelector:@selector(titleForSegmentAtIndex:)] {
...
60. Protocols inherit from other protocols:
@protocol MyProtocol <NSObject>
...
61. Conforming to protocol:
@interface MyClass: NSObject <MyProtocol>
...
@end
62. Adopt multiple protocols:
@interface MyClass: NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
...
@end
be aware, if there are too many protocols adopted in a class, it's a sign of bad design.
63. Some protocols are used to indicate non-hierarchical similarities between classes.
64. Protocols are also useful in situations where the class of an object isn't known, or needs to stay hidden.
65. Some types like NSInteger and NSUInteger, are defined differently depending on the target architecture.
it's best practice to use these platform-specific types if you might be passing values across API boundaries.
66. C structures can hold primitive values.
67. Strings are represented by instances of the NSString class
NSString *str = @"Hello, World!";
68. The basic NSString class is immutable.
69. The NSMutableString class is the mutable subclass of NSString.
70. Numbers of represented by instances of the NSNumber class.
it's possible to create NSNumber instances using Objective-C literal syntax:
NSNumber *magicNumber = @42;
it's possible to request the scalar value using one of the accessor methods:
int scalarMagic = [magicNumber intValue];
note: NSNumber is actually a class cluster.
NSNumber class is itself a subclass of the basic NSValue, NSValue can also be used to represent pointers and structures.
71. @encode compiler directive:
typedef struct {
int i;
float f;
} MyIntegerFloatStruct;
struct MyIntegerFloatStruct aStruct;
aStruct.i = 42;
aStruct.f = 3.14;
NSValue *structValue = [NSValue value:&aStruct
withObjCType:@encode(MyIntegerFloatStruct)];
72. Most collections are objects.
collection classes use strong references to keep track of their contents.
73. NSArray, NSSet and NSDictionary classes are immutable, each has a mutable subclass to allow you to add or remove objects at will.
74. NSArray is used to represent an ordered collection of objects, the only requirement is that each item is an Objective-C object.
75. The arrayWithObjects: and initWithObjects: methods both take nil-terminated, variable number of arguments.
It's possible to truncate the list of items unintentionally if one of the provided values is nil.
76. It's possible to create an array using the Objective-C literal like this:
NSArray *someArray = @[firstObject, secondObject, thirdObject];
SHOULD NOT terminate the list of objects with nil when using this literal syntax.
if you do need to represent a nil value in it, should use the NSNull singleton class.
77. When try to access item of array using "objectAtIndex" method, should always check the number of items first:
if([someArray count] > 0) {
NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
}
78. NSArray class offers methods to sort its collected objects, because it is immutable, each of these methods returns
a new array containing the items in the sorted order.
79. Usage of NSMutableArray:
NSMutableArray *mutableArray = [NSMutableArray array];
[mutableArray addObject: @"gamma"];
...
[mutableArray replaceObjectAtIndex:0 withObject:@"epision"];
80. Sort a mutable array in place, without creating a secondary array:
[mutableArray sortUsingSelector:@selector(caseInsensitiveCompare:)];
81. Sets are unordered collections, they don't maintain order, and offer a performance improvement.
82. As with NSArray, the iniWithObjects: and setWithObjects: methods of NSSet both take a nil-terminated, variable number of arguments.
The mutable NSSet subclass is NSMutableSet.
83. About NSDictionary, it's best practice to use string objects as dictionary keys.
84. Creating dictionaries:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
someObject, @"anObject",
@"Hello, World!", @"hellowString",
@42, @"magicNumber",
someValue, @"aValue",
nil];
each object is specified before its key, and the list of objects and keys must be nil-terminated.
objectAtIndex" method, should always check the number of items first:
if([someArray count] > 0) {
NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
}
85. Like NSArray, NSDictionary also can be created in a literal form:
NSDictionary *dictionary = @{
@"anObject": someObject,
@"helloString": @"Hello, World!",
@magicNumber": @42,
@"aValue": someValue
};
and with out nil-terminated, the structure is just like Javascript object definition.
86. Query dictionary:
NSNumber *storedNumber = [dictionary objectForKey:@"magicNumber"];
if the object isn't found, nil will be returned.
we can also use subscript syntax alternative like this:
NSNumber *storedNumber = dictionary[@"magicNumber"];
87. Mutable version: NSMutableDictionary
[dictionary setObject:@another string" forKey:@"secondString"];
[dictionary removeObjectForKey:@"anObject"];
88.Representing nil with NSNull
NSArray *array = @[@"string", @42, [NSNull null]];
89. The NSArray and NSDictionary classes make it easy to write their contents directly to disk like this:
NSURL *fileURL = ...
NSArray *array = @[@"first", @"second", @"third"];
BOOL success = [array writeToURL:fileURL atomically:YES];
if(!success) {
//an error occured
}
if every contained object is one of the property list types( NSArray, NSDictionary, NSString, NSData, NSDate and NSNumber),
it's easy to recreate the entire hierarchy from disk:
NSURL *fileURL = ...
NSArray *array = [NSArray arrayWithContentsOfURL:fileURL];
if(!array) {
//an error occured
}
90. If need to persist other types of objects, we can use an archiver object such as NSKeyedArchiver, the only requirement to
create an archive is that each object must support the NSCoding protocol.
91. Many collection classes conform to the NSFastEnumeration protocol, including NSArray, NSSet and NSDictionary, syntax:
for (<type> <variable> in <colleciton>) {
...
}
92. If you use fast enumeration with a dictionary, you iterate over the dictionary keys like this:
for( NSString *eachKey in dictionary) {
id object = dictionary[eachKey];
NSLog(@"Object: %@ for key: %@", object,eachKey);
}
93. You cannot mutate a collection during fast enumeration.
94. It's also possible to enumeratemany Coca and Cocoa Touch collections by using an NSEnumerator object.
for (id eachObject in [array reverseObjectEnumerator]) {
...
}
95. It's also possible to iterate through the contents by calling the enumerator's nextObject method repeatedly like this:
id eachObject;
while ( (eachObject = [enumerator nextObject]) ) {
NSLog(@"Current object is: %@", eachObject);
}
96. Because it's a common programmer error to use the C assignment operator (=) when you mean the quality test operator (==),
the compiler will warn you if you set a variable in a conditional branch or loop, like this:
if (someVariable = YES) {
...
}
if you really want to do this, indicate this by placing the assignment in parentheses like this:
if ( (someVariable = YES ) ) {
...
}
97. Many collections support block-based enumeration.
98. Blocks are like closures or lambdas in other programming language.
99. Syntax of blocks:
^{
NSLog(@"This is a block");
}
100.You can declare a variable to keep track of a block, like this:
void (^simpleBlock)(void);
the same syntax as function pointers:)
101.Block can operate just like a method, can have arguments and return value:
^ double (double firstValue, double secondValue) {
return firstValue * secondValue;
}
102.Blocks can capture values from the enclosing scope
- (void)testMethod {
int anInteger = 42;
void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger);
};
testBlock();
}
103.The block cannot change the value of the original variable, or even the captured value (it's captured as a const variable)
104.Use __block variables to share storage:
if you need to be able to change the value of a captured variable from within a block, use __block storage type modifier on the original
variable declaration like this:
__block int anInteger = 42;
void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger);
}
anInteger = 84;
testBlock();
105.You can pass blocks as arguments to methods or functions, an simplify some tasks:
- (IBAction)fetchRemoteInformation:(id)sender {
[self showProgressIndicator];
XYZWebTask *task = ...
[task beginTaskWithCallbackBlock:^{
[self hideProgressIndicator];
}];
}
It's important to take care when capturing "self" because it's easy to create strong reference cycle.
106.A block should always be the last argument to a method.
107.We can use type definition to simplify block syntax, like this:
typedef void (^XYZSimpleBlock)(void);
108.We can use properties to keep track of blocks, like this:
@interface XYZObject: NSObject
@property (copy) void (^blockProperty)(void);
@end
109.It's possible to use type definition for block property declarations, like this:
typedef void (^XYZSimpleBlock)(void);
@interface XYZObject: NSObject
@property (copy) XYZSimpleBlock blockProperty;
@end
110.To avoid strong reference when capturing "self" in block, should use weak reference like this:
- (void)configureBlock {
XYZBlockKeeper * __weak weakSelf = self;
self.block = ^{
[weakSelf doSomething];
}
}
111.Blocks can simplify iteration:
NSArray *array = ...
[array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"Object at index %lu is %@", idx, obj);
}];
112.If the code in the enumeration block is process-intensive--and safe for concurrent execution-- can use this:
[array enumerateObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
...
}];
113.Block based method in NSDictionary:
NSDictionary *dictionary = ...
[dictionary enumerateKeysAndObjectsUsingBlock:^ (id key, id obj, BOOL *stop) {
NSLog(@"key:%@, value: %@", key, obj);
}];
114.Blocks can simplify concurrent tasks, you can create NSOperation instance to encapsulate a unit of work along with
any neccessary data, the add that operation to an NSOperationQueue for execution.
although you can create your own custom NSOperation subclass to implement complex tasks, it's also possible to use
the NSBlockOperation to create an operation using a block, like this:
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
..
}];
115.Queue:
//schedule task on main queue:
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[mainQueue addOperation:operation];
//schedule task on background queue:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
116.Schedule blocks on dispatch queues with Grand Central Dispatch:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSLog(@"Block for asynchronous execution");
});
117.Only programming error using exception, all other errors are represented by instances of the NSError class.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
rather than making the requirement that every possible error have a unique numeric code, Cocoa and CocoaTouch
errors are divided into domains.
example, the connection:didFailWithError: method above will privide an error from NSURLErrorDomain.
the error object also incudes a localized description.
118.Some Methods pass errors by reference:
- (BOOL)writeToURL:(NSURL *)aURL
options:(NSDataWritingOptions)mask
error:(NSError **)errorPtr;
//invoke
NSError *anyError;
BOOL success = [receivedData writeToURL:someLocalFileURL
options:0
error:&anyError];
if(!success) {
NSLog(@"Write failed with error: %@", anyError);
//present errors to user
}
119.It's important to test the return value of the method to see whether an error occured, don't just test whether the
error pointer was set to point to an error, it's not reliable.
120.Create your own errors:
first you need to define your own error domain, like this:
com.companyName.appOrFrameworkname.ErrorDomain
you'll also need to pick a unique error code for each error that may occur in your domain, along with a suitable
description, which is stored in the user info dictionary for the error, like this:
NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
NSString *desc = NSLocalizedString(@"Unable to...", @"");
NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: desc };
NSError *error = [NSError errorWithDomain:domain
code:-101
userInfo:userInfo];
121.If you need to pass back an error by reference as describe above your method signature should include a parameter for
a pointer to a pointer to an NSError object. should also use the return value to indicate success or failure, like this:
- (BOOL)doSomethingThatMayGenerateAnError:(NSError **)errorPtr {
...
//error occured
if (errorPtr) {
*errorPtr = [NSError errorWithDomain:...
code:...
userInfo:...];
}
return NO;
}
122.Exceptions are used for programming errors:
@try {
//do something that might throw an exception
}
@catch (NSException *exception) {
//deal with the exception
}
@finally {
//optional block of clean-up code
}
123.Some naming conventions:
NS -- Foundation (OSX and iOS) and Application Kit(OSX)
UI -- UIKit (iOS)
AB -- Address Book
CA -- Core Animation
CI -- Core Image
124.Method names do not have a prefix, and should start with a lowercase letter; camel case is used again for multiple words.
125.If a method includes an error pointer parameter to be set if an error occurred, this should be the last parameter to the method.
126.Accessor method names must follow conventions, the compiler automatically synthesizes the relevant getter and setter methods,
a getter method should use the same name as property, the exception to this rule is for Boolean properties, for which the getter
method should start with is.
127.the setter method for a property should use the form setPropertyname:
128.Althoug the @property syntax allows you to specify different accessor method names, you should only do so for situations like
a Boolean property. It's essential to follow the conventions described here, otherwise technques like Key Value Coding won't work.
129.Class factory methods should always start with the name of the class (without the prefix) that they create, with the exception
of subclasses of classes with existing factory methods. for example, NSArray, the factory methods start with array.
the NSMutableArray class doesn't define any of its own class-specific factory methods, so the factory methods for a mutable array
still begin with array.