Monday, September 10, 2012

Lập trình iPhone - Đối tượng NSMutableArray

Đối tượng NSMutableArray

I - Giới thiệu:

NSMutableArray là dối tượng dùng để quản lý 1 danh sách các đối tượng. NSMutableArray cho phép thêm, xoá, hoặc tính toán, thao tác trên các phần tử trong mảng.




II - Các thao tác trong NSMutableArray

A - Khởi tạo mảng:
+ arrayWithCapacity:
– initWithCapacity:

B- Chèn thêm phần tử vào mảng:
– addObject:
– addObjectsFromArray:
– insertObject:atIndex:
– insertObjects:atIndexes:

C - Xoá phần tử mảng:
– removeAlltrongObjects
– removeLastObject
– removeObject:
– removeObject:inRange:
– removeObjectAtIndex:
– removeObjectsAtIndexes:
– removeObjectIdenticalTo:
– removeObjectIdenticalTo:inRange:
– removeObjectsInArray:
– removeObjectsInRange:
– removeObjectsFromIndices:numIndices:

D- Thay đổi phần tử trong mảng:
– replaceObjectAtIndex:withObject:
– replaceObjectsAtIndexes:withObjects:
– replaceObjectsInRange:withObjectsFromArray:range:
– replaceObjectsInRange:withObjectsFromArray:
– setArray:

E- Sắp xếp phần tử trong mảng:
– exchangeObjectAtIndex:withObjectAtIndex:
– sortUsingDescriptors:
– sortUsingComparator:
– sortWithOptions:usingComparator:
– sortUsingFunction:context:
– sortUsingSelector:

III - Sử dụng:

1 - Khởi tạo mảng:

NSMutableArray *monhoc;

2 - Khởi tạo mảng với phần tử cho trước:


PHP Code:
NSMutableArray *monhoc = [[NSMutableArray alloc]initWithObjects:
                               @
"Web Doanh Nghiệp",
                               @
"Joomla",
                               @
"Lập trình Android",
                               @
"Lập trình iPhone"
                               
nil ]; 
3 - Đếm số phần tử trong mảng:

PHP Code:
int sopt = [monhoc count]; NSLog(@"%i"sopt); 
4 - Truy cập phần tử thứ n:

PHP Code:
NSString *phantuthu3; phantuthu3 = [monhoc objectAtIndex:3];   // Lập trình iPhone 
5 - Thêm phần tử:

[monhoc addObject:@"Lập trình Game trên iPhone"];
// tự động monhoc tăng thêm 1 phần tử nữa

6 - Xoá phần tử khỏi mảng:

PHP Code:
[monhoc removeObjectAtIndex:2];
 
// Xoá khỏi mảng Lập trình Android 

7- Duyệtphần tử trong mảng :

PHP Code:
int sopt = [monhoc count];
    
for( 
int i sopt i++ ){
   
NSLog(@"%@", [monhoc objectAtIndex:i] );

No comments:

Post a Comment