//
// main.m
// OC2_数组操作
//
// Created by zhangxueming on 15/6/11.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
//
#import <Foundation/Foundation.h>
//NSArray
int main(
int argc,
const char *
argv[]) {
@autoreleasepool {
NSArray *array1 = [[NSArray alloc] initWithObjects:
@"one",
@"two",
@"three",
@"four",
@"five", nil];
//计算数组的元素的个数
NSInteger cnt =
[array1 count];
NSLog(@"cnt = %li", cnt);
//获取指定位置的对象
id obj = [array1 objectAtIndex:
2];
NSLog(@"obj = %@", obj);
//添加数组元素
NSArray *array2 = [array1 arrayByAddingObject:
@"six"];
NSLog(@"array2 = %@", array2);
//将传入数组中的所有元素添加到数组中
NSArray *otherArray = [[NSArray alloc] initWithObjects:
@"hello",
@"world", nil];
NSArray *array3 =
[array1 arrayByAddingObjectsFromArray:otherArray];
NSLog(@"array3 = %@", array3);
//用给定的分割符连接数组中的元素
NSString *str = [array3 componentsJoinedByString:
@"##"];
NSLog(@"str = %@", str);
//判断是否包含某个对象
BOOL ret = [array3 containsObject:
@"hello"];
NSLog(@"ret = %i", ret) ;
//返回两个数组中第一个相同的对象
id obj2 =
[array3 firstObjectCommonWithArray:otherArray];
NSLog(@"obj2 = %@", obj2);
//返回传入对象在数组中第一次出现的位置
NSArray *array4 = [NSArray arrayWithObjects:
@"one",
@"two",
@"three",
@"one",
@"two", nil];
NSUInteger index = [array4 indexOfObject:
@"two"];
NSLog(@"index = %lu", index);
//返回传入对象在指定范围内第一次出现的位置
NSUInteger index2 = [array4 indexOfObject:
@"two" inRange:NSMakeRange(
2,
3)];
NSLog(@"index2 = %lu", index2);
//判断两个数组是否相等
BOOL ret3 =
[array2 isEqualToArray:array3];
NSLog(@"ret3 = %d", ret3);
//获取数组中的第一个元素
id obj3 =
[array4 firstObject];
NSLog(@"obj3= %@", obj3);
//获取数组中最后一个元素
id obj4 =
[array4 lastObject];
NSLog(@"obj4 = %@", obj4);
//数组的遍历
//方法一: 下标法
NSArray *array5 = @[
@"one",
@"two",
@"three",
@"four"];
NSUInteger len =
[array5 count];
for (NSInteger i=
0; i<len; i++
) {
NSLog(@"%@", [array5 objectAtIndex:i]);
}
//方法二: 枚举器法
//生成枚举器对象
NSEnumerator *enumerator =
[array5 objectEnumerator];
id item =
nil;
while (item =
[enumerator nextObject]) {
NSLog(@"item = %@", item);
}
//倒序遍历数组
NSEnumerator *reverseEnumerator =
[array5 reverseObjectEnumerator];
id item2 =
nil;
while (item2 =
[reverseEnumerator nextObject]) {
NSLog(@"item = %@", item2);
}
//方法三: 快速枚举法
for (id item
in array5) {
NSLog(@"%@", item);
}
//数组排序
NSArray *array6 = @[
@"one",
@"two",
@"three",
@"four",
@"five"];
NSArray *sortArray =
[array6 sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"sortArray = %@", sortArray);
//数组提取
NSArray *subArray = [array6 subarrayWithRange:NSMakeRange(
1,
3)];
NSLog(@"subArray = %@", subArray);
//以给定下标集合提取数组
NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] initWithIndex:
0];
[indexSet addIndex:2];
[indexSet addIndex:4];
NSArray *subArray2 =
[array6 objectsAtIndexes:indexSet];
NSLog(@"subArray2 = %@", subArray2);
}
return 0;
}
转载于:https://www.cnblogs.com/0515offer/p/4569775.html