首页 > 代码库 > NSArray - 数组
NSArray - 数组
// // main.m // OC04-task-07 // // Created by Xin the Great on 15-1-24. // Copyright (c) 2015年 Xin the Great. All rights reserved. // #import <Foundation/Foundation.h> #import "NSArray+Log.h" #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... ///////////////NSArray - 数组/////////////// //数组的创建, 使用alloc init创建和使用类方法创建功效是一样的,但是内存管理上不同 NSArray *arr1 = [[NSArray alloc] initWithObjects:@"1",@"2", nil]; NSLog(@"arr1 is %@",arr1); //类方法创建 NSArray *arr2 = [NSArray arrayWithObjects:@"11",@"22", nil]; NSLog(@"arr2 is %@",arr2); //此初始化方法使arr3只有一个元素 NSArray *arr3 = [NSArray arrayWithObject:@"我们在学IOS"]; NSLog(@"arr3 is %@",arr3); //创建一个人的对象 Person *jack = [[Person alloc] init]; jack.name = @"jack"; jack.age = 30; NSArray *arr4 = [NSArray arrayWithObject:jack]; NSLog(@"arr4 is %@",arr4); //通过已有的数组构造一个新的数组 NSArray *newArray = [NSArray arrayWithArray:arr2]; NSLog(@"newArray is %@",newArray); //数组的访问 //objectAtIndex: 根据下标取出元素,如果下标越界,程序崩溃(crash) Person *jack1 = [arr4 objectAtIndex:0]; NSLog(@"jack1 is %@",jack1); //通过元素取下标, 如果没有找到,则返回NSNotFound NSArray *arr5 = [NSArray arrayWithObjects:@"1",@"2",jack, nil]; // NSInteger index = [arr5 indexOfObject:jack]; // NSLog(@"index is %ld", index); NSInteger index = [arr5 indexOfObject:@"123"]; NSLog(@"index is %ld", index); //求数组的长度 NSInteger count = [arr5 count]; NSLog(@"count is %ld", count); //判断数组中是否存在某一个元素, BOOL isTrue = [arr5 containsObject:@"123"]; NSLog(@"isTrue is %d",isTrue); //将数组变成一个字符串 NSArray *arr6 = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil]; NSString *str = [arr6 componentsJoinedByString:@"-"]; NSLog(@"str is %@",str); //将字符串分割成数组 NSArray *arr7 = [str componentsSeparatedByString:@"-"]; NSLog(@"arr7 is %@",arr7); //获取第一个元素和最后一个元素 NSString *firstStr = arr7[0]; NSLog(@"firstStr is %@",firstStr); // NSString *lastStr = arr7[arr7.count - 1]; //最后一个元素 NSString *lastStr = [arr7 lastObject]; NSLog(@"lastStr is %@",lastStr); //简单写法 NSArray *arr8 = @[jack, @"2"]; NSString *value = http://www.mamicode.com/arr8[0];>NSArray - 数组
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。