Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
961 views
in Technique[技术] by (71.8m points)

objective c - Finding a particular instance in an array by a property

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

Currently I do it like this:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you know that there is only 1 instance with an id of 5, just add a break; at the end of the if statement after you have made your updates. This will terminate the loop iteration and is probably the most efficient.

You shouldn't worry too much about runtime performance without profiling.

To write less code, you can write the for as:

for (MyClass *myClass in myMutableArray) {

You may want to change away from using an array for your storage if you need to access individual items often anyway.

Also, don't do:

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

Because you're needlessly creating an instance that you never use and just gets thrown away.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...