NSArray和NSMutableArray
生活随笔
收集整理的這篇文章主要介紹了
NSArray和NSMutableArray
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.不可變數組(NSArray)的操作
? ?1.1.不可變數組的聲明,不可變數組生命有很多方式,這里只有最基本的一種
// 聲明一個數組 // 數組的元素可以是任意的對象 // 數組中裝的是對象的地址 NSArray * array = [[[NSArray alloc] initWithObjects:@"one",@"two",@"three", nil] autorelease];1.2.直接打印數組,會將數組的元素都打印出來
// 聲明一個數組 // 數組的元素可以是任意的對象 // 數組中裝的是對象的地址 NSArray * array = [[[NSArray alloc] initWithObjects:@"one",@"two",@"three", nil] autorelease];// 數組的遍歷 // 直接打印數組的時候,會將數組的每個元素都打印出來,在數組類中重寫了description方法,%@打印對象,就會獲得description方法的返回值 NSLog(@"my array is %@",array);1.3.數組的遍歷
? ? ? ? 1.3.1.枚舉器法遍歷數組
NSEnumerator * enumerator = [array objectEnumerator]; id obj; while(obj = [enumerator nextObject]){NSLog(@"枚舉器法進行數組的遍歷:%@",obj); }?1.3.2.foreach遍歷
for(id obj in array){NSLog(@"foreach遍歷數組元素是 :%@",obj); }?1.3.3.for遍歷
for(int i = 0; i < [array count];i++){NSLog(@"for方法返回的數組元素是:%@",[array objectAtIndex:i]); }2.可變數組(NSMutableArray)的操作,可變數組是不可變數組的子類,所以可變數組可以使用不可變數組的方法
? ?2.1.向可變數組中添加元素
NSMutableArray *mutableArray = [[[NSMutableArray alloc] init] autorelease]; [mutableArray addObject:@"haha"]; [mutableArray addObject:@"hoho"]; [mutableArray addObject:@"nienie"]; NSLog(@"mutableArray is %@",mutableArray);2.2.刪除元素 使用remove的一系列方法
[mutableArray removeObject:@"hoho"]; // 根據內容刪除數組對象 [mutableArray removeObjectAtIndex:0]; // 根據數組下標刪除對象 NSLog(@"刪除后mutableArray is %@",mutableArray);? ?2.3.交換兩個數組元素的位置
[mutableArray exchangeObjectAtIndex:0 withObjectAtIndex:1]; NSLog(@"交換位置后的mutableArray is %@",mutableArray);2.4.可變數組的遍歷,其他和NSArray一致
? ? ? ? 2.4.1.在枚舉器法正序遍歷和foreach方法遍歷數組中,不能去改變這個數組中元素的值,但是在可變數組的逆序遍歷中可以修改可變數組中的元素
NSMutableArray *testMutableAray = [[[NSMutableArray alloc] init] autorelease]; [testMutableAray addObject:@"張三"]; [testMutableAray addObject:@"李四"]; [testMutableAray addObject:@"王五"]; [testMutableAray addObject:@"趙六"];NSEnumerator * myenumerator = [testMutableAray reverseObjectEnumerator];NSString *str;while (str = [myenumerator nextObject]) {[testMutableAray removeLastObject]; } NSLog(@"%@",testMutableAray);? ?3.字符串和數組之間的轉化
? ? ? ? 3.1.將字符串分割成數組
NSString * mySubstr = @"I am a poor man"; NSLog(@"原始的字符串是:%@",mySubstr); NSArray * mySubArray = [mySubstr componentsSeparatedByString:@" "]; NSLog(@"分割后的數組是:%@",mySubArray);? 3.2.將數組拼接成字符串
// 將數組拼接成字符串 // 方法1. NSEnumerator * mySubEnumerator = [mySubArray reverseObjectEnumerator]; NSMutableArray * subMutableArray = [[[NSMutableArray alloc] init] autorelease]; id subObj; while (subObj = [mySubEnumerator nextObject]) {[subMutableArray addObject:subObj];NSLog(@"逆序后遍歷的字符串是:%@",subObj); }// 方法2 // componentsJoinedByString后面的“--”是字符串之間的連接符 NSString * joinedStr = [subMutableArray componentsJoinedByString:@"--"]; NSLog(@"拼接之后生成的新的數組是:%@",joinedStr);
轉載于:https://www.cnblogs.com/zwhFighting/p/4550783.html
總結
以上是生活随笔為你收集整理的NSArray和NSMutableArray的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用NSCondition实现多线程同步
- 下一篇: C#获取邮件客户端保存的邮箱密码