0

I'm trying to cast an object in an NSArray; the below loop clearly explains what I'm trying to achieve, but can I do it without a loop?

NSArray* inputs = [star activeStars];
for (Galaxy* object in inputs) {
    HBLogDebug(@"%@",object.name);
}

So I could perform searching in one line like below:

int foundInt = [inputs indexOfObject:@"somestar"];
YosiFZ
  • 7,792
  • 21
  • 114
  • 221
Gregor Isack
  • 1,111
  • 12
  • 25
  • Do you mean you want to find the element whose name property is equal to "somestar" without looping over the array and breaking when you find it? – Hichem BOUSSETTA Mar 11 '19 at 14:31
  • Yes, you're right! – Gregor Isack Mar 11 '19 at 14:31
  • I am not sure this is feasible, I'll think about it twice. It would have been better if you had a NSDictionary instead of NSArray where the key would be the name of the star, and the value would be the Galaxy object. It is like creating an index in a database to facilite the lookup of data based on that index. – Hichem BOUSSETTA Mar 11 '19 at 14:37
  • 1
    See the "Finding Objects in an Array" section of the `NSArray` documentation. – Willeke Mar 11 '19 at 14:59
  • You are looking for that https://developer.apple.com/documentation/foundation/nsarray/1408043-indexofobjectpassingtest?language=objc Using it like this: `NSUInteger index = [matches indexOfObjectPassingTest:^BOOL(Galaxy * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { return [obj name] == @"somestar";}];` – Larme Mar 11 '19 at 15:17
  • Fo one liners you need "kvc collection operators" https://nshipster.com/kvc-collection-operators/ [[star activeStars] valueForKeyPath:@"name"]; however if you need to filter the correct answer is above – Marek H Mar 11 '19 at 16:52

0 Answers0