2011年8月9日 星期二

Obj C notes

1. @interface
Used to declare a class. To declare a class MyClass inheriting MyParentClass, we can write
/* Code blocks begin */
@interface MyClass : MyParentClass {
}
+ ClassMethods:(type1)param1 :(type2)param2
- InstanceMethods:(type1)param1 :(type2)param2 SomeDescriptiveNotes:(type3)param3
// The word "SomeDescriptiveNotes" only stand for programmer read and will not influence any real behavior
/* Code blocks end */
2. @implementation : the body of a class
3. Instantiation :
1. MyClass *myCls = [[MyClass alloc] init];
2. MyClass *myCls = [[MyClass alloc] initWithSomeParameters];
3. MyClass *myCls = [MyClass new];
4. Protocol ==> C++ abstract class multiple inheritance or Java interface
5. Message forwarding
Implement a call passing behavior. When main send a message "Greeting" to ClassA, ClassA doesn't implement the message, and ClassB does, then ClassA can pass the "Greeting" message to ClassB without handling locally

6. Category
Behaving like inheritance, category adopt parent class's data, including private, and add/replace existing methods.
/* Code blocks begin */
@interface ParentClass (CategoryA) {
}
- CategoryA_method1;
- CategoryA_method2;
@end
/* Code blocks end */
The use of ParentClass with CategoryA can have CategoryA_method1 and CategoryA_method2 methods

7. Instance variable, property and synthesize
Use of property/synthesize ==> add special attribute(readonly/read-write/copy/assign/retain/atomic/nonatomic to instance variable
@interface ClassA : NSObject {
public:
int var1;
provate:
int var2;
}
@property (copy) int var1; // Declare var1 as "copy" attribute
@property (readonly) int var2; // Declare var2 as "readonly" attribute
/*** Note ***/
/* Copy, retain are reference to mutable subclass ? */
/* Copy : int x = 5; myClass.var1 = x; x = 10; var1 will be 5 */
/* Retain : int x = 5; myClass.var1 = x; x = 10; var1 will be 10 */


When synthesize a variable, it will generate "setter" and "getter" automatically
@synthesize var1;
/* Generate : void setVar1:(int)v1
int getVar1
*/

沒有留言: