通过属性在数组中查找特定实例 [英] Finding a particular instance in an array by a property

查看:94
本文介绍了通过属性在数组中查找特定实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 MyClass 的各种实例的数组,它有四个属性: int id int valueA int valueB int valueC 。有时,我需要修改一个特定实例的属性(对于这个例子,假设它是 id 等于 5 )。

I have an array containing various instances of MyClass, which has four properties: int id, int valueA, int valueB, and int valueC. On occasion, I need to modify a property for a specific instance (for this example let's say it is the one with id equal to 5).

目前我是这样做的:

MyClass *myClass = [[MyClass alloc] init];

for (int i = 0; i < [myMutableArray count]; i++)
{
    myClass = [myMutableArray objectAtIndex:i];

    if(myClass.id == 5)
    {
        myClass.valueA = 100;
        myClass.valueB = 200;
        myClass.valueC = 300;
        [myMutableArray replaceObjectAtIndex:i withObject: myClass];
    }
}

高效的)这样做的方法?

Is there a better (I am hesitant to say more efficient) way of doing this?

推荐答案

一个简单的,虽然冗长的方式来获得数组的特定成员一定是使用 indexOfObjectPassingTest:结合 objectAtIndex:

A straightforward, though wordy, way to get a particular member of the array by any criteria at all is to use indexOfObjectPassingTest: combined with objectAtIndex:

MyClass * theInstanceIWant;
theInstanceIWant = [myArray objectAtIndex:[dates indexOfObjectPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) {
                                                        return ([obj id] == 5);
                    }];

theInstanceIWant.valueA = 100;
theInstanceIWant.valueB = 200;
theInstanceIWant.valueC = 300;

无需使用 replaceObjectAtIndex:withObject: - theInstanceIWant 的名称指向数组中的实际对象,并且可以在数组中仍然存在的情况下更改其属性。

There's no need to use replaceObjectAtIndex:withObject: -- the name theInstanceIWant refers to the actual object in the array, and you can change its properties while it's still in the array.

(使用 NSArray 上的类别方法更加愉快。)

(This is made more pleasant with a category method on NSArray.)

- (id)WSSObjectPassingTest:(BOOL (^)(id obj, NSInteger idx, BOOL *stop))test
{
    NSUInteger testedIndex = [self indexOfObjectPassingTest:test];
    return [self objectAtIndex:testedIndex];
}

这篇关于通过属性在数组中查找特定实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆