三種集合類來收集cocoa對象(NSObject對象):
NSArray 用于對象有序集合(相當于是數組)
NSSet 用于對象無序集合
NSDictionary用于鍵值映射
以上三種集合類是不可變的(一旦初始化后,就不能改變)
以下是對應的三種可變集合類(這三種可變集合類是對應上面三種集合類的子類):
NSMutableArray
NSMutableSet
NSMutableDictionary
注:這些集合類只能收集cocoa對象(NSOjbect對象),如果想保存一些原始的C數據(例如,int, float, double, BOOL等),則需要將這些原始的C數據封裝成NSNumber類型的,NSNumber對象是cocoa對象,可以被保存在集合類中。
NSArray
Ordered collection of objects. Immutable. You cannot add or remove objects to it once it’s created.
Important methods:
+ (id)arrayWithObjects:(id)firstObject, ...; // nil terminated
- (int)count;
- (id)objectAtIndex:(int)index; // NSString *s1=[[myarray objectAtIndex: 0];
- (void)makeObjectsPerformSelector:(SEL)aSelector;
- (NSArray *)sortedArrayUsingSelector:(SEL)aSelector;
- (id)lastObject; // returns nil if there are no objects in the array (convenient)
注:
類方法arrayWithObjects 可以創建an autoreleased NSArray of the items.例如
@implementation MyObject
- (NSArray *)coolCats {
return [NSArray arrayWithObjects:@“Steve”, @“Ankush”, @“Sean”, nil];
}
@end
Other convenient create with methods (all return autoreleased objects):
[NSString stringWithFormat:@“Meaning of %@ is %d”, @“life”, 42];
[NSDictionary dictionaryWithObjectsAndKeys:ankush, @“TA”, janestudent, @“Student”, nil];
[NSArray arrayWithContentsOfFile:(NSString *)path];
-----創建數組 -----
//NSArray *array = [[NSArray alloc] initWithObjects:
@"One",@"Two",@"Three",@"Four",nil];
self.dataArray = array;
[array release];
//- (unsigned) Count;數組所包含對象個數;
NSLog(@"self.dataArray cound:%d",[self.dataArray count]);
//- (id) objectAtIndex: (unsigned int) index;獲取指定索引處的對象;
NSLog(@"self.dataArray cound 2:%@",[self.dataArray objectAtIndex:2]);
------ 從一個數組拷貝數據到另一數組(可變數級) -------
//arrayWithArray:
//NSArray *array1 = [[NSArray alloc] init];
NSMutableArray *MutableArray = [[NSMutableArray alloc] init];
NSArray *array = [NSArray arrayWithObjects:
@"a",@"b",@"c",nil];
NSLog(@"array:%@",array);
MutableArray = [NSMutableArray arrayWithArray:array];
NSLog(@"MutableArray:%@",MutableArray);
array1 = [NSArray arrayWithArray:array];
NSLog(@"array1:%@",array1);
//Copy
//id obj;
NSMutableArray *newArray = [[NSMutableArray alloc] init];
新聞熱點
疑難解答