标签:
什么是NSArray?
NSArray的使用注意
+ (instancetype)arrayWithArray:(NSArray *)array;
+ (id)arrayWithContentsOfFile:(NSString *)path;
+ (id)arrayWithContentsOfURL:(NSURL *)url;
NSArray直接使用NSLog()作为字符串输出时是小括号括起来的形式。
NSArray中不能存储nil,因为NSArray认为nil是数组的结束(nil是数组元素结束的标记)。nil就是0。0也是基本数据类型,不能存放到NSArray中。
NSArray *arr = [NSArray arrayWithObjects:@"lnj", nil ,@"lmj",@"jjj", nil];
NSLog(@"%@", arr);
输出结果:
(
lnj
)
- (NSUInteger)count;
- (id)objectAtIndex:(NSUInteger)index;
- (BOOL)containsObject:(id)anObject;
- (id)lastObject;
- (id)firstObject;
- (NSUInteger)indexOfObject:(id)anObject;
- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range;
自从2012年开始, Xcode的编译器多了很多自动生成代码的功能, 使得OC代码更加精简
数组的创建
objc [NSArray arrayWithObjects:@"Jack", @"Rose", @"Jim", nil];
objc @[@"Jack", @"Rose", @"Jim"];
数组元素的访问
objc [array objectAtIndex:0];
objc array[0];
---
NSArray *arr = @[p1, p2, p3, p4, p5];
for (int i = 0; i < arr.count; ++i) {
Person *p = arr[i];
[p say];
}
NSArray *arr = @[p1, p2, p3, p4, p5];
for (Person *p in arr) {
[p say];
}
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"obj = %@, idx = %lu", obj, idx);
Person *p = obj;
[p say];
}];
// 让数组中所有对象执行这个方法
// 注意: 如果数组中的对象没有这个方法会报错
// [arr makeObjectsPerformSelector:@selector(say)];
[arr makeObjectsPerformSelector:@selector(eat:) withObject:@"bread"];
NSArray *arr = @[@(1), @(9), @(5), @(2)];
NSArray *newArr = [arr sortedArrayUsingSelector:@selector(compare:)];
NSArray *arr = @[p1, p2, p3, p4, p5];
// 默认按照升序排序
NSArray *newArr = [arr sortedArrayWithOptions:NSSortConcurrent usingComparator:^NSComparisonResult(Person *obj1, Person *obj2) {
return obj1.age > obj2.age;
}];
NSLog(@"%@", newArr);
NSArray *arr = @[@"lnj", @"lmj", @"jjj", @"xcq"];
BOOL flag = [arr writeToFile:@"/Users/LNJ/Desktop/persons.plist" atomically:YES];
NSLog(@"%i", flag);
NSArray *newArr = [NSArray arrayWithContentsOfFile:@"/Users/LNJ/Desktop/persons.xml"];
NSLog(@"%@", newArr);
NSArray *arr = @[@"lnj", @"lmj", @"jjj", @"xcq"];
NSString *res = [arr componentsJoinedByString:@"*"];
NSLog(@"res = %@", res);
输出结果:
lnj*lmj*jjj*xcq
NSString *str = @"lnj-lmj-jjj-xcq";
NSArray *arr = [str componentsSeparatedByString:@"-"];
NSLog(@"%@", arr);
输出结果:
(
lnj,
lmj,
jjj,
xcq
)
标签:
原文地址:http://www.cnblogs.com/zhoudaquan/p/5017670.html