A,NSArray只存储Objective-C对象,而不能存储C语言中的基本数据类型,构造NSArray的时候需要记着以nil标示结尾。
NSMutableArray创建的是动态数组,可以随意添加删除元素,而NSArray一经创建不能添加删除。
#import
void print(NSArray *arr)
{
NSEnumerator *enu = [arr objectEnumerator];
id obj;
while (obj = [enu nextObject]) {
printf("%s\n", [[obj description] UTF8String]);
}
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//静态数组
NSArray *arr = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil];
printf("static array---------\n");
print(arr);
//动态数组
NSMutableArray *marr = [[NSMutableArray alloc] init];
[marr addObject:@"one"];
[marr addObject:@"two"];
[marr addObjectsFromArray:arr];
[marr addObject:@"three"];
[marr addObject:@"three"];
[marr removeObjectAtIndex:(NSUInteger)2];
[marr removeObject: @"three"];
printf("mutable array---------\n");
print(marr);
//排序
[marr sortUsingSelector:@selector(caseInsensitiveCompare:)];
printf("sorted mutable array----------\n");
print(marr);
[arr release];
[marr release];
[pool drain];
return 0;
}
运行结果如下:
static array---------
a
b
c
mutable array---------
one
two
b
c
sorted mutable array----------
b
c
one
two
总结:我们可以用Obj,Obj,Obj,... ,nil的方式来初始化一个NS数组,针对排序可以选择自定义的selector实现,而print函数中的NSEnumerator(类似迭代器)可以用来遍历数组。
B,NSDictionary字典类型与NSMutableDictionary动态字典类型#import
void print(NSDictionary *dic)
{
NSEnumerator *enu = [dic keyEnumerator];
id key;
while (key = [enu nextObject]) {
printf("%s => %s\n",
[[key description] UTF8String],
[[[dic objectForKey:key] description] UTF8String]);
}
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//静态字典
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:
@"one",[NSNumber numberWithInt:1],
@"two",[NSNumber numberWithInt:2],
@"three",[NSNumber numberWithInt:3],
nil];
printf("static dictionary--------\n");
print(dic);
//动态字典
NSMutableDictionary *mdic = [[NSMutableDictionary alloc] init];
[mdic setObject:@"http://blog.csdn.net/ciaos" forKey:@"ciaos"];
[mdic setObject:@"http://weibo.com/littley" forKey:@"penjin"];
[mdic addEntriesFromDictionary:dic];
[mdic setObject:@"http://localhost" forKey:@"unknown"];
[mdic removeObjectForKey:@"unknown"];
printf("mutable dictionary---------\n");
print(mdic);
[dic release];
[mdic release];
[pool drain];
return 0;
}
运行结果如下,可以看出显示结果和插入顺序没有关系,这和C#中的字典类型一样。
static dictionary--------
3 => three
1 => one
2 => two
mutable dictionary---------
penjin => http://weibo.com/littley
3 => three
ciaos => http://blog.csdn.net/ciaos
2 => two
1 => one