zoukankan      html  css  js  c++  java
  • 对象集合 一

    1,创建数组。

    NSArray是固定数组,NSMutableArray是可变数组。

    创建固定数组

    NSArray *listOfLetters = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];

    也可用类似的方法创建可变数组,NSMutableArray是NSArray的子类。下面是一些最常用的方法以及解释。

    - (id)initWithObjects:(const id [])objects count:(NSUInteger)cnt; Initializes an array with the specified objects and count

     

    - (id)initWithObjects:(id)firstObj, ...

     NS_REQUIRES_NIL_TERMINATION;

    Initializes an array with the specified nil- terminated list of objects

     

    - (id)initWithArray:(NSArray *)array;

    Initializes an array using another array

     

    - (id)initWithArray:(NSArray *)array copyItems:(BOOL)flag;

    Initializes an array using another array and creates new copies of each object

     

    - (id)initWithContentsOfFile:(NSString *)path;

    Initializes an array with the contents of a local file

     

    - (id)initWithContentsOfURL:(NSURL *)url;

    Initializes an array with the contents at a URL

    代码例子。

     

    //创建打印固定数组。

            NSArray *listOfLetters1 = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];

            NSLog(@"listOfLetters1 = %@", listOfLetters1);

    //这里注意NSNumber是对象

            NSNumber *number1 = [NSNumber numberWithInt:1];

            NSNumber *number2 = [NSNumber numberWithInt:2];

            NSNumber *number3 = [NSNumber numberWithInt:3];

            NSMutableArray *listOfNumbers1 = [[NSMutableArray alloc] initWithObjects:number1, number2, number3, nil];

            NSLog(@"listOfNumbers1 = %@", listOfNumbers1);

    //极少用的方法

            id list[3];

            list[0] = @"D";

            list[1] = @"E";

            list[2] = @"F”;

    //这里给分配了数组的长度。

            NSMutableArray *listOfLetters2 = [[NSMutableArray alloc] initWithObjects:list count:3];

            NSLog(@"listOfLetters2 = %@", listOfLetters2);

     

    2,数组引用对象。

    得到数组内的第一个对象

    NSString *stringObject1 = [listOfLetters objectAtIndex:0];

    得到数组内最后一个对象

    NSString *stringObject2 = [listOfLetters lastObject];

    你也可以通过内容找到数组的下标

    NSUInteger position = [listOfLetters indexOfObject:@"B”];

    具体代码

            NSMutableArray *listOfLetters = [NSMutableArray arrayWithObjects:@"A", @"B", @"C", nil];

            NSString *stringObject1 = [listOfLetters objectAtIndex:0];

            NSLog(@"stringObject1 = %@", stringObject1);

            

            NSString *stringObject2 = [listOfLetters lastObject];

            NSLog(@"stringObject2 = %@", stringObject2);

            NSUInteger position = [listOfLetters indexOfObject:@"B"];

            NSLog(@"position = %lu", position);

    3,获取数组个数。

    用数组.count就可以,

    具体代码例子。

     

    NSMutableArray *listOfLetters = [NSMutableArray arrayWithObjects:@"A", @"B", @"C", nil];

            NSLog(@"listOfLetters has %lu elements", listOfLetters.count);

    4,遍历数组

    我们就不用书上的方法了,这里直接创建数组。

    NSArray *listOfObjects = @[@"A",@"B",@"C",@"D”];

    然后遍历它。

    for(NSMutableString *s in listOfObjects){

                NSLog(@"This string in lowercase is %@", [s lowercaseString]);

            }

    这里 用lowercaseString把字符串变小写了。

     

    也可以用@selector向数组发送方法,用withObject来传递参数

    [listOfObjects makeObjectsPerformSelector:@selector(appendString:)

                                   withObject:@"-MORE”];

    需要确认方法appendString可用。

    利用blocks遍历数组。

    [listOfObjects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)

    {

        NSLog(@"object(%lu)'s description is %@",idx, [obj description]);

    }];

    具体代码例子

            NSMutableString *string1 = [NSMutableString stringWithString:@"A"];

            NSMutableString *string2 = [NSMutableString stringWithString:@"B"];

            NSMutableString *string3 = [NSMutableString stringWithString:@"C"];

     

    //        NSArray *listOfObjects = [NSArray arrayWithObjects:string1, string2, string3, nil];  

       

    // 这里string1 等必须是可变字符串,写死是不行的 appendString方法会报错。

            NSArray *listOfObjects = @[string1, string2, string3];

            for(NSMutableString *s in listOfObjects){

                NSLog(@"This string in lowercase is %@", [s lowercaseString]);

            }

            [listOfObjects makeObjectsPerformSelector:@selector(appendString:)

                                           withObject:@"-MORE"];

     

            [listOfObjects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

                NSLog(@"object(%lu)'s description is %@",idx, [obj description]);

            }];

    这里enumerateObjectsUsingBlock 的用法详细说一下,block类似其他语言里的闭包,闭包就是能够读取其它函数内部变量的函数。obj,是数组里的值,idx是下标,当*stop为真时跳出循环,例子。

            NSArray* arr = @[@"A", @"B", @"C" , @"D", @"",];

            [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL* stop) {

                if (idx == 1) {

                    *stop = 1;

                }

                NSLog(@"obj = %@, idx = %lu, stop = %hhd", obj, (unsigned long)idx, *stop);

            }];

    5,数组排序。

    创建Person类,然后创建数组。

    person类大概是这个样子,.h文件

    #import <Foundation/Foundation.h>

    @interface Person : NSObject

    @property(strong) NSString *firstName;

    @property(strong) NSString *lastName;

    @property(assign) int age;

    -(id)initWithFirstName:(NSString *)fName lastName:(NSString *)lName andAge:(int)a;

    -(void)reportState;

    @end

    Person.m

    #import "Person.h"

    @implementation Person

    @synthesize firstName, lastName, age;

    -(id)initWithFirstName:(NSString *)fName lastName:(NSString *)lName andAge:(int)a{

        self = [super init];

        if (self) {

            self.firstName = fName;

            self.lastName = lName;

            self.age = a;

        }

        return self;

    }

    -(void)reportState{

        NSLog(@"This person's name is %@ %@ who is %i years old", firstName, lastName, age);

    }

    @end

    创建数组

            //Instantiate Person objects and add them all to an array:        

     

            Person *p1 = [[Person alloc] initWithFirstName:@"Rebecca"

     

                                                  lastName:@"Smith"

     

                                                    andAge:33];

     

            Person *p2 = [[Person alloc] initWithFirstName:@"Albert"

     

                                                  lastName:@"Case"

     

                                                    andAge:24];

     

            Person *p3 = [[Person alloc] initWithFirstName:@"Anton"

     

                                                  lastName:@"Belfey"

     

                                                    andAge:45];

     

            Person *p4 = [[Person alloc] initWithFirstName:@"Tom"

     

                                                  lastName:@"Gun"

     

                                                    andAge:17];

     

            Person *p5 = [[Person alloc] initWithFirstName:@"Cindy"

     

                                                  lastName:@"Lou"

     

                                                    andAge:6];

     

            Person *p6 = [[Person alloc] initWithFirstName:@"Yanno"

     

                                                  lastName:@"Dirst"

     

                                                    andAge:76];

     

            

     

            NSArray *listOfObjects = [NSArray arrayWithObjects:p1, p2, p3, p4, p5, p6,  nil];

    可以使用NSSortDescriptor排序,例如

    //Create three sort descriptors and add to an array:

    NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:@"age"

                                                          ascending:YES];

    NSSortDescriptor *sd2 = [NSSortDescriptor sortDescriptorWithKey:@"lastName"

                                                          ascending:YES];

    NSSortDescriptor *sd3 = [NSSortDescriptor sortDescriptorWithKey:@"firstName"

                                                          ascending:YES];

    NSArray *sdArray1 = [NSArray arrayWithObjects:sd1, sd2, sd3, nil];

    传入你要排序的字段和是否正序排列。

    通过描述符对数组进行排序。

    NSArray *sortedArray1 = [listOfObjects sortedArrayUsingDescriptors:sdArray1];

    注意,sdArray1。

    具体代码示例。

    @autoreleasepool {

            //Instantiate Person objects and add them all to an array:        

            Person *p1 = [[Person alloc] initWithFirstName:@"Rebecca"

                                                  lastName:@"Smith"

                                                    andAge:33];

            Person *p2 = [[Person alloc] initWithFirstName:@"Albert"

                                                  lastName:@"Case"

                                                    andAge:24];

     

            Person *p3 = [[Person alloc] initWithFirstName:@"Anton"

                                                  lastName:@"Belfey"

                                                    andAge:45];

     

            Person *p4 = [[Person alloc] initWithFirstName:@"Tom"

                                                  lastName:@"Gun"

                                                    andAge:17];

     

            Person *p5 = [[Person alloc] initWithFirstName:@"Cindy"

                                                  lastName:@"Lou"

                                                    andAge:6];

     

            Person *p6 = [[Person alloc] initWithFirstName:@"Yanno"

                                                  lastName:@"Dirst"

                                                    andAge:76];

            NSArray *listOfObjects = [NSArray arrayWithObjects:p1, p2, p3, p4, p5, p6,  nil];

            NSLog(@"PRINT OUT ARRAY UNSORTED");

            [listOfObjects makeObjectsPerformSelector:@selector(reportState)];

            //Create three sort descriptors and add to an array:

            NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:@"age"

     

                                                                  ascending:YES];

            NSSortDescriptor *sd2 = [NSSortDescriptor sortDescriptorWithKey:@"lastName"

     

                                                                  ascending:YES];

            NSSortDescriptor *sd3 = [NSSortDescriptor sortDescriptorWithKey:@"firstName"

     

                                                                  ascending:YES];

            NSArray *sdArray1 = [NSArray arrayWithObjects:sd1, sd2, sd3, nil];

            NSLog(@"PRINT OUT SORTED ARRAY (AGE,LASTNAME,FIRSTNAME)");

            NSArray *sortedArray1 = [listOfObjects sortedArrayUsingDescriptors:sdArray1];

            [sortedArray1 makeObjectsPerformSelector:@selector(reportState)];

            NSArray *sdArray2 = [NSArray arrayWithObjects:sd2, sd1, sd3, nil];

            NSArray *sortedArray2 = [listOfObjects sortedArrayUsingDescriptors:sdArray2];

            NSLog(@"PRINT OUT SORTED ARRAY (LASTNAME,FIRSTNAME,AGE)");

    [sortedArray2 makeObjectsPerformSelector:@selector(reportState)];

        }

    6,数组查询。

    一旦有你的谓词设置,可利用filteredArrayUsingPredicate获取查询值,并发送谓词作为参数。

    例如

    NSArray *arraySubset = [listOfObjects filteredArrayUsingPredicate:predicate];

     

    Person类不变,看main里的代码。

        @autoreleasepool {

     

            //Instantiate Person objects and add them all to an array:        

     

            Person *p1 = [[Person alloc] initWithFirstName:@"Rebecca"

                                                  lastName:@"Smith"

                                                    andAge:33];

     

            Person *p2 = [[Person alloc] initWithFirstName:@"Albert"

                                                  lastName:@"Case"

                                                    andAge:24];

     

            Person *p3 = [[Person alloc] initWithFirstName:@"Anton"

                                                  lastName:@"Belfey"

                                                    andAge:45];

     

            Person *p4 = [[Person alloc] initWithFirstName:@"Tom"

                                                  lastName:@"Gun"

                                                    andAge:17];

     

            Person *p5 = [[Person alloc] initWithFirstName:@"Cindy"

                                                  lastName:@"Lou"

                                                    andAge:6];

            Person *p6 = [[Person alloc] initWithFirstName:@"Yanno"

                                                  lastName:@"Dirst"

                                                    andAge:76];

            NSArray *listOfObjects = [NSArray arrayWithObjects:p1, p2, p3, p4, p5, p6,  nil];

            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 30"];

            NSArray *arraySubset = [listOfObjects filteredArrayUsingPredicate:predicate];

            NSLog(@"PRINT OUT ARRAY SUBSET");

    [arraySubset makeObjectsPerformSelector:@selector(reportState)];

        }

    7,操纵数组内容。就是一堆现成的方法,本别是给数组插入值,insertObject,前端插入,指定位置替换值replaceObjectAtIndex,更改位置,exchangeObjectAtIndex,根据下标和内容移除值,移除第一个值,移除最后一个值,移除所有值。

    代码示例

            NSMutableArray *listOfLetters = [[NSMutableArray alloc] init];

     

            [listOfLetters addObject:@"A"];

     

            [listOfLetters addObject:@"B"];

     

            [listOfLetters addObject:@"C"];

     

            NSLog(@"OBJECTS ADDED TO ARRAY: %@", listOfLetters);

     

            [listOfLetters insertObject:@"a"

     

                                atIndex:0];

     

            NSLog(@"OBJECT 'a' INSERTED INTO ARRAY: %@", listOfLetters);

     

            [listOfLetters replaceObjectAtIndex:2

     

                                     withObject:@"c"];

     

            NSLog(@"OBJECT 'c' REPLACED 'C' IN ARRAY: %@", listOfLetters);

     

            [listOfLetters exchangeObjectAtIndex:0

     

                               withObjectAtIndex:2];

     

            NSLog(@"OBJECT AT INDEX 1 EXCHANGED WITH OBJECT AT INDEX 2 IN ARRAY: %@", listOfLetters);

     

            [listOfLetters removeObject:@"A"];

     

            NSLog(@"OBJECT 'A' REMOVED IN ARRAY: %@", listOfLetters);

     

            [listOfLetters removeObjectAtIndex:1];

     

            NSLog(@"OBJECT AT INDEX 1 REMOVED IN ARRAY: %@", listOfLetters);

     

            [listOfLetters removeLastObject];

     

            NSLog(@"LAST OBJECT REMOVED IN ARRAY: %@", listOfLetters);

     

            [listOfLetters removeAllObjects];

     

            NSLog(@"ALL OBJECTS REMOVED IN ARRAY: %@", listOfLetters);

    8,将数组值写入文件。

            NSArray *listOfObjects = [NSArray arrayWithObjects:@"A", @"B", @"C", [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil];

            NSString *filePathName = @"/Users/Shared/array.txt";

            [listOfObjects writeToFile:filePathName

                            atomically:YES];

    我们看到array.txt虽然是txt文件,但写入的数组是xml格式的。

    9,从文件读取内容。紧接着上段代码,我们看到我们读取出来的是一个数组。

            NSString *filePathName = @"/Users/Shared/array.txt";

            NSArray *listOfObjects = [[NSArray alloc] initWithContentsOfFile:filePathName];

            NSLog(@"%@", listOfObjects);

  • 相关阅读:
    同步的原则
    我心中的final
    令人"哇"的内部类(一)内部类的设计意义
    令人"哇"的内部类(三)嵌套类
    共享资源问题的解决方案(一)加锁机制
    令人"哇"的内部类(二 )内部类访问外围类
    volatile关键字
    同步控制块
    高质量C++/C 编程指南一
    5、数据表的创建与更新(续)
  • 原文地址:https://www.cnblogs.com/guanliyang/p/3908400.html
Copyright © 2011-2022 走看看