转载自:http://1058813598.diandian.com/post/2011-12-24/10271590
http://blog.sina.com.cn/s/blog_7b9d64af01019ex5.html
/* 初始化方法:
1.init返回一个空数组
2.initWithArray从已有数组初始化
3.initWithContentsOfFile//从plist文件加载
4.initWithContentsOfUrl//从网络地址上获取
5.initWithObject用一个对象初始化
6.initWithObjects从多对象初始化
self.theDataArray=[[NSMutableArray alloc]initWithCapacity:5];//指定有五个元素初始化
*/
/*打印第一个元素:
NSLog(@"the object is:%@",[theDataArray firstObjectCommonWithArray:theDataArray]);
*/
/*打印最后一个元素:
NSLog(@"the object is:%@",[theDataArray lastObject]);
*/
/*枚举所有元素,方法一:
for (NSString * theStr in theDataArray) {
NSLog(@"%@:",theStr);
}
*/
/*枚举所有元素,方法二:
for (int i=0,i<[theDataArray count],i++) {
//NSLog(@"%@:",[theDataArray objectAtIndex:i]);
}
*/
/* 枚举所有元素,方法三,用枚举器:
NSEnumerator *enumerator=[theDataArray objectEnumerator];
id obj;
while (obj =[enumerator nextObject]) {
NSLog(@"%@",obj);
}
*/
/* //添加元素
[theDataArray addObject:@"这是新添加的元素"];//从最后开始添加
*/
/* //从指定索引插入元素
[theDataArray insertObject:@"this is inerted object" atIndex:0];//是插入到指定 索引的前面
*/
/* //修改.更新元素
[theDataArray replaceObjectAtIndex:0 withObject:@"new obj"];//指定索引修改
*/
/* //判断数组是否包含某个对象
if ([theDataArray containsObject:@"selectiont"]) {
NSLog(@"the object selection is contained in array");
}
else{
NSLog(@"not contain");
}
*/
/* //获取元素索引
NSLog(@"the idx is:%i",[theDataArray indexOfObject:@"selection"]);
*/
/*//数组元素排序
方法一:
NSArray *theTempArr=[[NSArray alloc] initWithArray:[theDataArray
sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];
*/
//[theDataArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; // or @selector(compare:)
/*//数组元素排序
方法二:
NSLog(@"before sorted array:%@",theDataArray);
NSCountedSet *cset=[[NSCountedSet alloc] initWithArray:theDataArray];
NSArray *theTempArr=[[NSArray alloc] initWithArray:[[cset allObjects]sortedArrayUsingSelector:@selector(compare:)]];
NSLog(@"after sorted array:%@",theTempArr);
*/
/* //对数组对象进行排序 NSSortDescriptor
NSSortDescriptor *sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];//@“name”是对象属性
[theDataArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];//返回排序好的数组
//还可以用自定义方法:[theDataArray sortUsingSelector:@selector(custom Method:)];
-(NSInteger)customMethod:(someObject *)otherObj{
NSCompareResult compareResult=[self.name compare:otherObj.name];
if(compareResult == NSOrderedSame) return 0;
if(compareResult == NSOrderedAscending) return 1;
else return -1;
}
*/
/* //对象数组过滤(NSPredicate)
NSArray *keyArray=[[NSArray alloce]initWtihObjects:@"A",@"B",nil];
for (NSString *key in keyArray)
{
//定义规则:
NSPredicate *apredicate=[NSPredicate predicateWithFormat:@"SELF.name
beginswith[c] %@",key]; //SELF.name是对象属性,beginswith[c] %@",key
表示选出name以key开头的对象
//或者 :
NSPredicate *apredicate=[NSPredicate
predicateWithFormat:@"SELF.name contains [c] %@",key]; //contains[c]
%@",key 表示选出name中包含有key的对象
//或者 :
NSInteger age=20;
NSPredicate *apredicate=[NSPredicate predicateWithFormat:@"SELF.age > %i",age]; // 表示选出age>20的对象
//或者 :
NSString * matchStr=@"hel*";
NSPredicate *apredicate=[NSPredicate predicateWithFormat:@"SELF.name like %@",matchStr]; // 表示选出name中包含与字符串matchStr相似的对象
NSArray *newArr=[theDataArray filteredArrayUsingPredicate:apredicate];
[theDataDict setValue:newArr forKey:key];
}
*/
/* //删除数组元素
NSMutableArray *tempArray=[[NSMutableArray alloc]initWithObjects:@"one",@"tow",@"threr",nil];
[tempArray removeObjectAtIndex:0];//从指定索引移除
[tempArray removeAllObjects];//移除所有元素
[tempArray removeLastObject];//移除最后那个元素
[tempArray removeObjectsInArray:newArray];//移除指定数组中元素
[tempArray removeObjectsAtIndexes: NSIndexSet *__strong)];//从所选择的索引中移除
*/
加入元素到NSMutableDictionary中:
- (void)addCard:(AddressCard *)theCard forKey:(NSString *)theKey{
[_bookDictionary setObject:theCard forKey:theKey];
}
注意:当_bookDictionary中不存在key为theKey的元素时,则添加,否则覆盖。
遍历NSMutableDictionary中元素:
- (void)printBook{
for (id akey in [_bookDictionary allKeys]) {
AddressCard *singleCard= (AddressCard *)[_bookDictionary objectForKey:akey];
[singleCard print];
}
}
查找NSMutableDictionary中元素:
- (AddressCard *)findCardByName:(NSString *)theName{
for (id akey in [_bookDictionary allKeys]) {
AddressCard *theCard= (AddressCard *)[_bookDictionary objectForKey:akey];
if ([[theCard name] caseInsensitiveCompare:theName ]==NSOrderedSame){
return theCard;
}
}
return Nil;
}
使用时:
AddressCard *theCard= [myBook findCardByName:@"Tom1"];// 查找元素
if (theCard!=Nil) {
[theCard print];
}
根据key值删除NSMutableDictionary中元素:
- (void) removeCard:(NSString *)theKey{
[_bookDictionary removeObjectForKey:theKey];
}
删除NSMutableDictionary中所有元素:
- (void) removeAllCard{
[_bookDictionary removeAllObjects];
}
返回NSMutableDictionary中所有元素个数:
- (int)cardsCount{
return [_bookDictionary count];
}
排序NSMutableDictionary中元素:
放在NSMutableDictionary中的元素,进行遍历的顺序和存入的时候的顺序是不一定相同的。
所以,要进行排序输出。比如按照薪水的从低到高进行排序输出:
- (NSArray *)sortBySalaryForDictionary{
NSArray *sortedKeys= [_bookDictionary keysSortedByValueUsingSelector:@selector(compareBySalaryForDictionary:)];
return sortedKeys;
}
在类AddressCard类中,加入compareBySalaryForDictionary方法:
- (NSComparisonResult) compareBySalaryForDictionary:(id)element{
if (salary>[element salary]) {
return NSOrderedDescending;
}else if (salary<[element salary]) {
return NSOrderedAscending;
}else{
return NSOrderedSame;
}
}
可以看到,使用keysSortedByValueUsingSelector方法,返回的是排序后,的键。
那么,在使用时,按照key来进行排序输出:
NSArray *sortedKeys=[myBook sortBySalaryForDictionary];
for (NSString *theKey in sortedKeys) {
AddressCard *theCard=[myBook findCardByName:theKey];
[theCard print];
}
NSDictionary转换NSMutableDictionary
// Override point for customization after app launch
// create an immutable array
NSArray *arr = [NSArray arrayWithObjects: @"one", @"two", @"three", nil ];
// create a mutable copy, and mutate it
NSMutableArray *mut = [arr mutableCopy];
[mut removeObject: @"one"];
//[mut release];
NSMutableArray *mut1 = [mut mutableCopy];
[mut1 removeObjectAtIndex:0];
[mut1 release];
[mut release];
NSMutableArray *mut2 = [NSMutableArray arrayWithObjects:@"A", @"B", nil];
NSMutableArray *mut2_immut = [mut2 copy];
//crash here
//[myArray_immut removeObjectAtIndex:0];
[mut2_immut release];
// Copys object, result is mutable
NSMutableArray *mut2_mut = [mut2 mutableCopy];
[mut2_mut removeObjectAtIndex:0];
[mut2_mut release];
深度复制
目标:把NSDictionary对象转换成NSMutableDictionary对象,对象内容是字符串数组,需要实现完全复制(深复制)。
如果调用NSDictionary的mutableCopy方法,可以得到一个NSMutableDictionary对象,但这只是浅复制,如果我们修改NSDictionary中数组内的值(当然,数组必须是NSMutableArray),会发现,NSMutableDictionary对象内数组的值也跟着更改了。我们需要增加一个mutableDeepCopy方法来实现深复制,在该方法中,循环复制每一个元素。
要实现这一功能,有两种方法,一是继承,二是使用category。category与继承的区别在于,使用category并不是新建一个类,而是在原类的基础上增加一些方法(使用的时候还是用原类名),这样,我们就不需要修改已经在其他源文件中写好的类名,只需要导入h头文件,再把复制方法修改成我们新增的方法即可。
一、新建Objective-C category文件,我这Category填MutableDeepCopy,Category on填NSDictionary,所以生成的文件是NSDictionary+MutableDeepCopy.h和NSDictionary+MutableDeepCopy.m,生成的文件名很容易理解。
二、两文件源代码:
NSDictionary+MutableDeepCopy.h
C++代码 收藏代码
#import <Foundation/Foundation.h>
@interface NSDictionary (MutableDeepCopy)
-(NSMutableDictionary *)mutableDeepCopy;
//增加mutableDeepCopy方法
@end
NSDictionary+MutableDeepCopy.m:
C++代码 收藏代码
#import "NSDictionary+MutableDeepCopy.h"
@implementation NSDictionary (MutableDeepCopy)
-(NSMutableDictionary *)mutableDeepCopy
{
NSMutableDictionary *dict=[[NSMutableDictionary alloc] initWithCapacity:[self count]];
//新建一个NSMutableDictionary对象,大小为原NSDictionary对象的大小
NSArray *keys=[self allKeys];
for(id key in keys)
{//循环读取复制每一个元素
id value=[self objectForKey:key];
id copyValue;
if ([value respondsToSelector:@selector(mutableDeepCopy)]) {
//如果key对应的元素可以响应mutableDeepCopy方法(还是NSDictionary),调用mutableDeepCopy方法复制
copyValue=[value mutableDeepCopy];
}else if([value respondsToSelector:@selector(mutableCopy)])
{
copyValue=[value mutableCopy];
}
if(copyValue==nil)
copyValue=[value copy];
[dict setObject:copyValue forKey:key];
}
return dict;
}
@end
测试:
C++代码 收藏代码
#import <Foundation/Foundation.h>
#import "NSDictionary+MutableDeepCopy.h"
//导入头文件
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *arr1=[[NSMutableArray alloc] initWithObjects:@"aa",@"bb",@"cc", nil];
NSDictionary *dict1=[[NSDictionary alloc] initWithObjectsAndKeys:arr1,@"arr1", nil];
NSLog(@"%@",dict1);
NSMutableDictionary *dict2=[dict1 mutableCopy];
//浅复制
NSMutableDictionary *dict3=[dict1 mutableDeepCopy];
//深复制
[arr1 addObject:@"dd"];
NSLog(@"%@",dict2);
NSLog(@"%@",dict3);
}
return 0;
}