zoukankan      html  css  js  c++  java
  • OC系列foundation Kit基础-NSArray

    一.NSArray数组创建

    1.通过构造方法创建数组

    a.initWithObjects创建数组

    Person *p = [[Person alloc]init];
    NSArray *arr = [[NSArray alloc]initWithObjects:@"one",@"two",@"three", nil];
    NSLog(@"arr is %@",arr);
    

      输出:

    2016-06-27 15:19:16.573 OcTest[830:552500] arr is (
        one,
        two,
        three
    )
    Program ended with exit code: 0
    

    b.initWithArray创建数组

    NSArray *arr = [[NSArray alloc]initWithObjects:@"one",@"two",@"three",nil];
    NSArray *arr1 = [[NSArray alloc]initWithArray:arr];
    NSLog(@"arr is %@",arr1);
    

      输出同上

    c.带拷贝的创建数组

    NSArray *arr1 = [[NSArray alloc]initWithArray:arr copyItems:NO];

    2.通过类方法创建数组(与其它数据结构类似)

    3.数组解析

    a.数组可以装任意对象,存储的是对象的地址

    b.私有对象,自定义对象打印调用的是description方法,字符串调用的也是description方法,打印的是本身

    c.带拷贝的创建数组中,copyItems为NO时,和上面的通过数组创建数组是一样的,当为YES时,即深拷贝,相当于对对象进行复制,产生一个新的对象,那么就有两个指针分别指向两个对象。当一个对象改变或者被销毁后拷贝出来的新的对象不受影响.要实现深拷贝,Person对象需要实现NSCoping protocol,并且要实现copWithZone这个方法:

    在Person类头文件中声明NSCoping协议,并且我们创建一个name属性

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject<NSCopying>
    @property(copy) NSString *name;
    @end
    

      在Person类实现类中实现copyWithZone方法

    @implementation Person
    
    -(id)copyWithZone:(NSZone *)zone
    {
        Person *p = [Person allocWithZone:zone];
        p.name = self.name;
        return p;
    }
    @end

    二.数组遍历

    以数组arr为例

    NSArray *arr = [[NSArray alloc]initWithObjects:@"one",@"two",@"three",nil];
    

    1.枚举器法

    NSEnumerator *enu = [arr objectEnumerator];
    id obj;
    while(obj = [enu nextObject]){
    NSLog(@"%@",obj);
    }

    2.快速遍历法

    id obj;
    for (obj in arr){
    NSLog(@"%@",obj);
    }
    

    3.i遍历法

    int i = 0;
    int count = [arr count];
            
    for(i;i< count;++i){
       NSLog(@"%@",[arr objectAtIndex:i]);
    }
    

      输出结果:

    2016-06-27 15:58:59.054 OcTest[953:696924] one
    2016-06-27 15:58:59.055 OcTest[953:696924] two
    2016-06-27 15:58:59.055 OcTest[953:696924] three
    Program ended with exit code: 0
    未来的你会感谢今天努力的自己 ------Alen
  • 相关阅读:
    关于盒模型的外边距padding和内边距margin
    CSS概述(最详细!!!)
    关于html的基本知识
    Maven学习(1)-什么是Maven
    IntelliJ IDEA+Github+Maven+Jenkins+SipringBoot+VUE搭建Web开发环境样例(2)-创建一个简单的查询数据库项目
    IntelliJ IDEA+Github+Maven+Jenkins+SipringBoot+VUE搭建Web开发环境样例(1)-安装与配置
    YARN(待了解)
    Mesos(待了解)
    Kubernetes-中文文档地址(收藏)
    Jenkins学习(4)-Jenkins的API(收藏)
  • 原文地址:https://www.cnblogs.com/kaihuacheng/p/5616151.html
Copyright © 2011-2022 走看看