Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...