年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1881|回复: 0

OC数组NSArray的基本使用与介绍

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2014-3-22 19:45:16 | 显示全部楼层 |阅读模式
    1. //
    2. //  main.m
    3. //  NSArray-1
    4. //
    5. //  Created by yusian on 14-3-22.
    6. //  Copyright (c) 2014年 小龙虾论坛. All rights reserved.
    7. //
    8. #import <Foundation/Foundation.h>
    9. int main()
    10. {
    11. /***********NSArray***********/
    12.    
    13.     // 1、使用类方法arrayWithObject初始化数组,只能赋值单个元素
    14.     NSArray * a1 = [NSArray arrayWithObject:@"yusian"];
    15.    
    16.     // NSArray * a1 = [[NSArray alloc] init];该数组永远为空
    17.    
    18.     // 快速创建数组的方法,该方法后面不需要加nil,Xcode编译器特性,参照数组的赋值方法
    19.     // NSArray * a1 = @[@"yusian", @"com", @"oc"];
    20.    
    21.     NSLog(@"%@", a1);
    22.    
    23.     // 2、使用类方法arrayWithObjects初始化数组,可赋值任意个元素数,nil标记元素赋值结束
    24.     NSArray * a2 = [NSArray arrayWithObjects:@"yusian.com", @"Objective-C", nil];
    25.    
    26.     NSLog(@"%@", a2);
    27.    
    28.     // 3、[a2 count]为取数组a2中元素个数的get方法,可使用点语法访问
    29.     NSLog(@"Element count of a2 is %ld", a2.count);
    30.    
    31.     // 4、NSArray中元素的访问
    32.     NSLog(@"%@", [a2 objectAtIndex:0]);
    33.    
    34.     NSLog(@"%@", a2[1]);
    35.    
    36. /**********NSMutableArray***********/
    37.     // 1、创建可变数组的常用方法,可变数组不可使用@[];方式初始化,@[]只能用于不可变数组
    38.     NSMutableArray * ma1 = [NSMutableArray arrayWithObjects:@"Father", @"Mother", @"Sian", @"Txt", nil];
    39.    
    40.     NSLog(@"%@", ma1);
    41.    
    42.     // 2、添加元素
    43.     [ma1 addObject:@"Son"];
    44.    
    45.     // 3、删除元素
    46.     [ma1 removeObject:@"Son"];
    47.     // [ma1 removeObjectAtIndex:4];
    48.     // [ma1 removeAllObjects];
    49.     // [ma1 removeAllObjects];
    50.    
    51.     // 4、数组元素遍历
    52.     // for循环遍历
    53.     for (int i = 0; i < ma1.count; i++) {
    54.    
    55.         NSLog(@"%@", ma1[i]);
    56.         
    57.     }
    58.    
    59.     // for循环( id obj in ma1)
    60.     for ( id obj in ma1) {
    61.    
    62.         NSLog(@"%@", obj);
    63.         
    64.     }
    65.    
    66.     // 数组遍历方法实现遍历
    67.     [ma1 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    68.         
    69.         NSLog(@"%@", obj);
    70.         
    71.         if (idx == 0) {
    72.             *stop = YES;
    73.         }
    74.     }];
    75.    
    76.    
    77.     return 0;
    78. }
    复制代码

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-5-6 03:27 , Processed in 0.042227 second(s), 19 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表