对象集合 一

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]);

}];

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);

对象集合 一,布布扣,bubuko.com

时间: 2024-08-03 15:35:11

对象集合 一的相关文章

MVC传递数据-传递对象或对象集合

前言 本文主要介绍从View(或者js)文件向Controller提交对象或者对象集合,比如,将表格中的一行数据作为一个对象提交,或将多行数据作为一个集合提交到Controller. 回顾 从View(或者js)文件向Controller提交数据,你可能见过以下几种方式: 将提交的数据附在url地址后面 $.ajax({ type: "POST", url: "/InviteBid/UpdateBidZRecord/?JudgeBidId=" + JudgeBidI

JS-window对象集合

<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>window对象集合——慕课网总结</title> <style type="text/css"> td{ border: 1px solid #4169E1; } caption{ background-color: lightsteelblue; padding:

实现对象集合与DataTable的映射

最近在研究ASP.NET MVC,跟我的项目经理探究以后,他更偏向于使用ADO.NET而不是ORM,所以自己想做一个Model与DataTable的映射程序,以便以后使用mvc使用到,自己才疏学浅,如果有更好的方法,希望博友们可以指出. 实现映射的前提条件是DataTable里的列名要和自己对象中的属性名一致,才能达到映射的效果. 首先来实现DataTable向对象集合的转换: public class ModelAdapter    {        public static IList<T

jsWindow 对象 Window 对象 Window 对象表示浏览器中打开的窗口。 如果文档包含框架(frame 或 iframe 标签),浏览器会为 HTML 文档创建一个 window 对象,并为每个框架创建一个额外的 window 对象。 注释:没有应用于 window 对象的公开标准,不过所有浏览器都支持该对象。 Window 对象集合 集合 描述 frames[] 返回窗口中所有命

一.JSX简介 JSX就是Javascript和XML结合的一种格式.React发明了JSX,利用HTML语法来创建虚拟DOM.当遇到<,JSX就当HTML解析,遇到{就当JavaScript解析. 如下(JS写法) var child1 = React.createElement('li', null, 'First Text Content'); var child2 = React.createElement('li', null, 'Second Text Content'); var

隐式类型、对象集合初始化、匿名类型

隐式类型和对象集合初始化器是在C# 3.0中引入的. 1 隐式类型 var关键字,主要还是编译器根据变量的值来推断其类型. 1.1隐式类型的局部变量 1 class Program 2 { 3 static void Main(string[] args) 4 { 5 var stringvariable="learning hard"; 6 stringvariable=2; 7 } 8 } 其实当你把鼠标放在var上面的时候,还是可以看到其类型的. 使用隐式类型时有一些限制,包括一

Intent之对象传递(Serializable传递对象和对象集合)

Android中Intent传递类对象提供了两种方式一种是 通过实现Serializable接口传递对象,一种是通过实现Parcelable接口传递对象. 要求被传递的对象必须实现上述2种接口中的一种才能通过Intent直接传递. Intent中传递这2种对象的方法: Bundle.putSerializable(Key,Object); //实现Serializable接口的对象 Bundle.putParcelable(Key, Object); //实现Parcelable接口的对象 一.

利用反射与dom4j读取javabean生成对应XML和读取XML得到对应的javabean对象集合

转自:http://blog.csdn.net/zhao19861029/article/details/8473245 首先实现生成对应的JAVAbean的XML文件方法 /** * DMO4J写入XML * @param obj 泛型对象 * @param entityPropertys 泛型对象的List集合 * @param Encode XML自定义编码类型(推荐使用GBK) * @param XMLPathAndName XML文件的路径及文件名 */ public void wri

C#高级知识点概要(3) - 特性、自动属性、对象集合初始化器、扩展方法、Lambda表达式和Linq查询

1.特性(Attributes) 特性(Attributes),MSDN的定义是:公共语言运行时允许你添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型.字段.方法和属性等.Attributes和Microsoft .NET Framework文件的元数据保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为.例如,在一个方法前标注[Obsolete]特性,则调用该方法时VS则会提示该方法已过期的警告,如下图: 又如,在.Net Re

Intent之对象传递(Parcelable传递对象和对象集合)

接着上一篇文章,下面我们讨论一下如何利用Parcelable实现Intent之间对象的传递 一.实现对象传递 首先创建User.java实现Parcelable接口: package org.yayun.demo; import java.io.Serializable; import android.R.integer; import android.os.Parcel; import android.os.Parcelable; public class User implements Pa