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
#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 = arr8[0];
NSLog(@"value is %@",value);
}
return 0;
}