1

In swift i am using this code to get particular object for a particular value

if let layer = self.layers.first(where: {$0.id == id}) { }

I want to use this same in objective-c. How should i get a object from array of objects for particular value

4
  • what is layer here? Is it some kind of array of modal ? Commented May 23, 2018 at 10:20
  • yeah it is an array of modal Commented May 23, 2018 at 10:25
  • Added an answer. Commented May 23, 2018 at 10:26
  • I would recommend this lib github.com/google/functional-objc because Objective-C is missing real functional interfaces. Commented May 23, 2018 at 10:38

3 Answers 3

2

You can use NSPredicate in Objective-C to filter an array.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", id];
id layer = [[self.layers filteredArrayUsingPredicate:predicate] firstObject]
Sign up to request clarification or add additional context in comments.

Comments

1

The predicateWithFormat solution is short, but not as type-safe as Swift.

To make it a bit more type-safe you could use indexOfObjectPassingTest.

Assuming you have:

@interface MyLayer
@property int layerID;
@end

NSArray<MyLayer *> *layers = @[...];
int layerIDToFind = 123;

You can write:

NSUInteger index = [layers indexOfObjectPassingTest:^BOOL(MyLayer *layer, NSUInteger idx, BOOL *stop) {
    return layer.layerID == layerIDToFind;
}];
if (index != NSNotFound) {
    MyLayer *layer = layers[index];
    // ... act on the layer ...
}

Comments

-1
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", id];

NSArray *result = [self.layers filteredArrayUsingPredicate:predicate];

if result.count > 0
{
    id  layer = [result firstObject].id
}

2 Comments

how you get .id value from array "result".
i have change that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.