Thứ Sáu, 28 tháng 6, 2013

LẬP TRÌNH OBJECTIVE-C - part 4

5.     Categories, Protocols, Delegate

a. Categories
-       Là đặc điểm nếu bạn muốn mở rộng lớp bằng cách thêm mới vào lớp một phương thức. Khi bạn làm việc quen với OOP thì bạn sẽ thấy đây là một trong những thuộc tính vô cùng hữu ích của Objective C, kể cả ngay khi bạn không có mã nguồn của lớp nhưng bạn vẫn hoàn toàn có thể thêm phương thức cho lớp như thường thông qua thuộc tính này. Đặc điểm này làm giảm đi đáng kể sự kế thừa phức tạp trong C++ khi việc kế thừa chỉ để phục vụ cho việc thêm mới một phương thức. Mặt khăc việc chia mã nguồn trên nhiều files cũng giúp ích đáng kể trong việc phát triển.
-       Tên của category phải là duy nhất
-       Có thể thêm bao nhiêu lần mở rộng lơp từ category là không giới hạn nhưng với tên là duy nhất.
-       Thông thể bổ xung biến thành phần bằng category.
-       Có thể sử dụng category để tạo ra các phương thức private. Nếu cần.
-       Cú pháp:
@interface ClassToAddMethodsTo (category)
//methods go here
@end

-       Ví dụ như :
@interface NSString (reverse)
-(NSString *) reverseString;
@end
 
@implementation NSString (reverse)
-(NSString *) reverseString {
  NSMutableString *reversedStr;
  int len = [self length];
  // Auto released string
  reversedStr = [NSMutableString stringWithCapacity:len];    
  // Probably woefully inefficient...
  while (len > 0)
    [reversedStr appendString:
         [NSString stringWithFormat:@"%C", [self characterAtIndex:--len]]];  
  return reversedStr;
}
@end

#import <Foundation/Foundation.h>
#import "NSString+Reverse.h"
int main (int argc, const char * argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  NSString *str  = [NSString stringWithString:@"Fubar"];
  NSString *rev;
  NSLog(@"String: %@", str);
  rev = [str reverseString];
  NSLog(@"Reversed: %@",rev);
  [pool drain];
  return 0;
}
Kết quả :

b. Frotocols (giao thức)
-          Objective-C cho phép bạn xác định các giao thức, thực hiện các kê khai các method dự kiến sẽ được sử dụng cho một tình huống cụ thể.
-          Một lớp giao diện khai báo cáo các hàm (methods) và các thuộc tính (proproties) thì gắn liền với lớp đó. Còn với một giao thức, thì ngược lại sử dụng để khai báo các method và properties độc lập với bất lớp nào khác.
-          Tất cả các class trong giao thức đều là required methods.
-          Cú pháp :
@protocol ProtocolName
// list of methods and properties
@end

-          Giao thức bao gồm cả method, thuộc tính

-          Ví dụ trên developer.apple.com
Đây là về biểu đồ hình tròn: gồm 3 thuộc tính :
@protocol XYZPieChartViewDataSource
- (NSUInteger)numberOfSegments;
- (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;
@optional
- (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
- (BOOL)shouldExplodeSegmentAtIndex:(NSUInteger)segmentIndex;
@required
- (UIColor *)colorForSegmentAtIndex:(NSUInteger)segmentIndex;
@end
   
      Gọi giao thức
@interface XYZPieChartView : UIView
@property (weak) id <XYZPieChartViewDataSource> dataSource;
@end

-          ́ thừa từ các giao thức khác :
@protocol MyProtocol <NSObject>
...
@end

@interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
...

Thứ Năm, 27 tháng 6, 2013

LẬP TRÌNH OBJECTIVE-C - part 3

4.  Class, objects, method cơ bản

a. Class:


-          File .h (Header File) là file quản lý các khai báo liên quan, cung cấp cho chúng ta cái nhìn về mặt tổng quan của code. Về lớp, loại, chức năng, khai báo hằng số, thuộc tính
-           File .m (Source File ) là file mở rộng được thừa kế từ header file, chứa nội dung chính bao gồm code ojective-C
* File .h (Header File)
@interface SimpleClass : NSObject
@end

-          Tại lớp này chúng ta khai báo lớp có tên là SimpleClass, được kế thừa NSObject.
@interface Person : NSObject
@property NSString *firstName;
@property NSString *lastName;
@end

-          Đối tượng Person có 2 thuộc tính : firstName, lastName đều là biến con trỏ (*) thuộc kiểu chuỗi NSString, kết thúc dòng code bằng dấu (;). Lớp Person thêm 1 thuộc tính mới yearOfBirth là chữ số
@end
@property NSNumber *yearOfBirth;
//Or
@property int yearOfBirth;

* File .m (Source File )
-          Chúng ta có file XYZPerson.h
@interface XYZPerson : NSObject
@property (readonly) NSString *firstName;
@property (readonly) NSString *lastName;
- (void)sayHello;
@end

-          Class kế thừa class “XYZPerson.h”
#import "XYZPerson.h"
@implementation XYZPerson
- (void)sayHello {
NSLog(@"Hello, World!");
}
@end

b. Method
Hàm cơ bản
-          Hàm trong C:
void SomeFunction();
-          Hàm trong Objective-C
- (void)someMethod;

- (void)someMethod {
NSString *myString = // get a string from somewhere...
}

Hàm có tham số truyền vào
-          Hàm trong C:
void SomeFunction(SomeType value);

-          Hàm trong Objective-C
- (void)someMethodWithValue:(SomeType)value;

- (void)someMethodWithValue:( NSString *)value {
NSLog(@"%@",value);
}

-          Tương tự với nhiều tham số
- (void)someMethodWithFirstValue:(SomeType)value1 secondValue:(AnotherType)value2;

Hàm số trả về
-          Trong C
int magicNumber {
return 42;
}

-          Trong Objective-C
- (int) magicNumber {
return 42;
}

-          Hàm gọi nhau trong cùng class
@implementation XYZPerson
- (void)sayHello {
[self saySomething:@"Hello, world!"];
}
- (void)saySomething:(NSString *)greeting {
NSLog(@"%@", greeting);
}
@end

c. Object
-          Khởi tạo object mới
NSString* myString = [NSString string];
NSString* myString = [[NSString alloc] init];
NSNumber* value = [[NSNumber alloc] initWithFloat:1.0];
// string1 will be released automatically
NSString* string1 = [NSString string];
// must release this when done
NSString *someString = @"Hello, World!";
NSString *someString = [NSString stringWithCString:"Hello, World!"
encoding:NSUTF8StringEncoding];
NSString* string2 = [[NSString alloc] init];
[string2 release];

-        Tạo đối tượng động:
-       hàm này trả về là id, đây là từ khóa đặc biết trong Objective-C (http://developer.apple.com định nghĩa là “some kind of object”). Theo tôi hiểu rằng đây là 1 dạng đối tượng đặc biệt giống với NSObject * nhưng nó không có dấu *
+ (id)alloc;
//or
- (id)init;

-          alloc (xem phần 7 – quản lý bộ nhớ) : nó gọi tới hàm init
NSObject *newObject = [[NSObject alloc] init];
tài liệu tham khảo

Thứ Tư, 26 tháng 6, 2013

LẬP TRÌNH OBJECTIVE-C - part 2

2. Các cấu trúc điều khiển

-          Các phép toán thường dùng
Phép toán so sánh
Phép toán
Mô tả
==
bằng
!=
Không bằng
> 
Lớn hơn
< 
Nhỏ hơn
>=
Lớn hơn hoặc bằng
<=
Nhỏ hơn hoặc bằng


Phép toán logic
Phép toán
Mô tả
!
khác
&&
||
Hoặc

-          If/else
if (condition) {
         //statement(s) if the condition is true;
}
else {
//statement(s) if the condition is not true;
  }

-          For
for (counter; condition; update counter) {
         //statement(s) to execute while the condition is true;
}

-          For In
for (Type newVariable in expression ) {
         //statement(s);
}
// or
//Type existingVariable ;
for (existingVariable in expression) {
//statement(s);
}
-          Sdụng khi
Ø  NSFastEnumeration
Ø  NSArray, NSSet
Ø  NSDictionary
Ø  NSManagedObjectModel

-          While
while (condition) {
         //statement(s) to execute while the condition is true
}

-          Do While
do {
         //statement(s) to execute while the condition is true
} while (condition);

-          Jump statement
Ø  Return; dừng thực hiện và trả về hàm gọi đến hàm dừng thực hiện này
Ø  Break; dừng vòng lặp
Ø  Continue; bỏ qua phần còn lại và bắt đầu lại từ đầu trong vòng lặp
Ø  Goto

Ø  Exit(); thoát khỏi chương trình

3. Array

Tạo mảng:
-          NSArray
NSArray *myColors;
myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
-          NSMutableArray
NSMutableArray *myColors;
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
-          Xử dụng arrayWithObject để tạo ra các đối  tượng item, ở đây tôi tạo mới 1 đối tượng mảng với 4 đuối tượng con kiểu String là red, green, blue, yellow. Và nil nằm cuối cùng, nếu không có nil nằm cuối cùng sẽ gây ra lỗi.
-          Khi khỏi tạo thi NSArray tạo ra mảng và không thể thay đổi, còn NSMutableArray thì ngược lại tức là cho phép thay đổi nội dung của mảng.

Tính số lượng đối tượng con trong mảng
NSLog (@"Number of elements in array = %lu", [myColors count]);

Xuất ra
Number of elements in array = 4

Xử lý các phần tử trong mảng
NSArray *myColors;
int i;
int count;

myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
count = [myColors count];
for (i = 0; i < count; i++)
NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);
Xuất ra
Element 0 = Red
Element 1 = Green
Element 2 = Blue
Element 3 = Yellow

Duyệt mảng nhanh
NSArray *myColors;
NSString *color;

myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
for (color in myColors)
NSLog (@"Element = %@", color);

Xuất ra
Element 0 = Red
Element 1 = Green
Element 2 = Blue
Element 3 = Yellow
Thêm phần tử mới vào mảng
NSMutableArray *myColors;

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
[myColors addObject: @"Indigo"];
[myColors addObject: @"Violet"];

-          Chèn phần tử vào mảng với số thứ tự
NSMutableArray *myColors;
int i;
int count;

myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
[myColors insertObject: @"Indigo" atIndex: 1];
[myColors insertObject: @"Violet" atIndex: 3];

count = [myColors count];
for (i = 0; i < count; i++)
NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);

Xuất ra
Element 0 = Red
Element 1 = Indigo
Element 2 = Green
Element 3 = Violet
Element 4 = Blue
Element 5 = Yellow

Sắp xếp các phần tử trong mảng
NSMutableArray *myColors = [NSMutableArray arrayWithObjects: @"red", @"green", @"blue", @"yellow", nil];
NSArray *sortedArray;
sortedArray = [myColors sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

-          Mảng được sắp xếp theo hàm localizedCaseInsensitiveCompare, ngoài ra còn có các hàm sắp xếp khác như NSOrderedAscending, NSOrderedSame or NSOrderedDescending

Xóa phần tử từ mảng
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

-          Xóa theo vị trị số thứ tự
[myColors removeObjectAtIndex: 0];

-          Xóa phần tử theo giá trị của phần tử cụ thể
[myColors removeObject: @"Red"];

-          Xóa tất cả phần tử trong mảng theo giá trị cụ thể của phần tử cần xóa
myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", @"Red", @"Red", nil];

[myColors removeObjectIdenticalTo: @"Red"];

-          Xóa tất cả các phần tử trong mảng
[myColors removeAllObjects];

-          Xóa phần tử cuối cùng trong mảng
[myColors removeLastObject];
tài liệu tham khảo