如何获取NSArray的最后一个对象 [英] How to get the last object of an NSArray
问题描述
所以我有一个数组,项目的数量可以变化。我想知道如果有反正我可以得到一个 NSArray
的最后一个对象?我想到有一个 int
计数器来跟踪数组中的项目数量,这似乎太麻烦了。
So I have an array which the amount of items could vary. I was wondering if there is anyway I can get the last object of an NSArray
? I did think of having like an int
counter to trace the amount of items in the array however that seems too much of a hassle.
有没有人知道比这更好?
Does anyone know anyway that's better than this?
推荐答案
扩展一点问题,有几种情况下,可能需要一个数组的最后一个对象,
Expanding a bit on the question, there are several situations in which one could need the last object of an array, with different ways to obtain it.
如果只是想获取对象的标准Cocoa程序,则这将执行:
If one just wants to get the object in course of a standard Cocoa program, then this will do it:
[myArray lastObject]
为了解决计数器的问题 - 不需要自己实现:
To address the concern of the counter - no need to implement one's own, either:
NSUInteger myCount = [myArray count];
使用键值编码(KVC)
如果需要通过KVC访问数组的最后一个对象,该故事需要一点解释。
Using key-value coding (KVC)
In case one needs to access the last object of an array through KVC, the story requires a bit of explanation.
首先,请求正常键的值数组将创建一个新数组,该数组由数组中每个对象的键的值组成。换句话说,从数组请求键 lastObject
将使数组向每个数组发送 valueForKey:
对象使用 lastObject
键。除了不是预期的结果,它也可能会抛出异常。
First, requesting the value of a normal key from an array will create a new array consisting of the values of that key for each of the objects in the array. In other words, a request for the key lastObject
from an array will make the array send valueForKey:
to each of the objects using the key lastObject
on them. Apart from not being the intended result, it will also likely throw an exception.
因此,如果真的需要发送一个键到数组本身内容),密钥需要在前面加上 @
-sign。这告诉数组,键是为数组本身,而不是其内容。
So in case one really needs to send a key to the array itself (as opposed to its contents), the key needs to be prepended with an @
-sign. This tells the array that the key is intended for the array itself, and not its contents.
键因此必须具有 @lastObject
的形式,并使用如下:
The key therefore has to have the form @lastObject
, and be used like this:
NSArray *arr = @[@1, @2, @3];
NSNumber *number = [arr valueForKey: @"@lastObject"];
在类别描述符
如何在实际程序中使用这个键是一种情况,其中数组数组需要通过每个内部数组中的 last 对象进行排序。
上面的键只用于排序描述符:
The above key is simply used in the sort descriptor:
NSArray *arrayOfArrays = @[@[@5, @7, @8], @[@2, @3, @4, @6], @[@2, @5]];
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey: @"@lastObject" ascending: YES];
NSArray *sorted = [arrayOfArrays sortedArrayUsingDescriptors: @[sd]];
在谓词
为了过滤数组数组,键可以直接在谓词中使用:
In a predicate
Likewise, in order to filter an array of arrays, the key can be used directly in a predicate:
NSPredicate *pred = [NSPredicate predicateWithFormat: @"self.@lastObject > 5"];
NSArray *filtered = [arrayOfArrays filteredArrayUsingPredicate: pred];
人们更喜欢离开 self
out可以简单地使用格式 @@ lastObject> 5
People preferring to leave the self
-part out can simply use the format @"@lastObject > 5"
这篇关于如何获取NSArray的最后一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!