如何从数组中只获取一种类型的对象?

时间:2021-02-27 03:35:05

(Xcode IOS) - I'm trying to make a method which prefetches all the images and loads them into a tableView before scrolling (using SDWebImage). Anyways:

(Xcode IOS) - 我正在尝试制作一个预取所有图像的方法,并在滚动之前将它们加载到tableView中(使用SDWebImage)。无论如何:

I have an array of messages and each "message" is composed of a few different keys, PFFile, dateCreated, sender, etc...

我有一系列消息,每个“消息”由几个不同的密钥组成,PFFile,dateCreated,sender等...

What I need to do is take this array of @[ [PFFile], [dateCreated], [other info] ] -> @[ [PFFile] ]

我需要做的是取这个@ [[PFFile],[dateCreated],[其他信息]] - > @ [[PFFile]]

In other words, I need to make an array of just the PFFiles from the entire array. I was thinking of something like this (pseudocode)

换句话说,我需要从整个数组中创建一个只有PFFiles的数组。我在考虑这样的事情(伪代码)

self.urls = [self.messages objectsWithKey:@[PFFiles]];

self.urls = [self.messages objectsWithKey:@ [PFFiles]];

2 个解决方案

#1


1  

It sounds like you are asking how to filter an array.

听起来你在问如何过滤数组。

self.urls = [self.messages objectsAtIndexes:[self.messages indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [obj isKindOfClass:[PFFile class]];
}]];

I like this syntax because you can use a block to return YES/NO if the object passes any sort of test you might want to write and it's a one-liner.

我喜欢这种语法,因为你可以使用一个块来返回YES / NO,如果对象通过了你可能要编写的任何类型的测试而且它是一行的。

#2


0  

How about using combination of NSDictionary and NSArray ? You can put your array objects in a dictionary object.

如何使用NSDictionary和NSArray的组合?您可以将数组对象放在字典对象中。

#1


1  

It sounds like you are asking how to filter an array.

听起来你在问如何过滤数组。

self.urls = [self.messages objectsAtIndexes:[self.messages indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [obj isKindOfClass:[PFFile class]];
}]];

I like this syntax because you can use a block to return YES/NO if the object passes any sort of test you might want to write and it's a one-liner.

我喜欢这种语法,因为你可以使用一个块来返回YES / NO,如果对象通过了你可能要编写的任何类型的测试而且它是一行的。

#2


0  

How about using combination of NSDictionary and NSArray ? You can put your array objects in a dictionary object.

如何使用NSDictionary和NSArray的组合?您可以将数组对象放在字典对象中。