0

I seem to be struggling this morning with this one. I have a NSArray that is filled with data. Pretty simple so far. Ultimately I need to retrieve one or more of the items out of the array to simply display on the device. Below

NSArray *myViews = viewsArray;   
NSString *activeView = [myViews valueForKey:@"Active"];

I know the Array is correct but for some reason unbeknown to myself I can get one of the items out of the array and set it so I can use it else where. Perhaps a scope issue.

My Array looks like this;

 [0]
    NSObject
    appViewName = (NSString *) @"AcmeAPP"
    appActive = (NSString *) @"True"

I have also tried looping over the array but that doesn't seem to work either. Clearly I'm missing something.

Zev Eisenberg
  • 8,080
  • 5
  • 38
  • 82
Jeremy
  • 366
  • 5
  • 15
  • possible duplicate of [Difference between objectForKey and valueForKey?](http://stackoverflow.com/questions/1062183/difference-between-objectforkey-and-valueforkey) – Rambatino Sep 01 '14 at 09:31

4 Answers4

1

The problem here is that you're trying to get a "valueForKey", which means you've incorrectly declared your "array" which actually needs to be a "NSDictionary" object.

NSArray does not have keys. NSDictionary does.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • 2
    You can use valueForKey with Array. http://iosdevtips.co/post/80598241763/valueforkey-nsarray – Matz Aug 31 '14 at 20:22
  • Thanks michael, its been a while since I touched objective c. Clearly. I have achieved the above result in a UITable view which uses the above. But what you are suggesting is to user NSDictionary instead of NSArray? – Jeremy Aug 31 '14 at 20:29
  • @Matz very interesting, but freaking weird behaviour. – keeshux Sep 01 '14 at 01:01
1

If you want to use key-value pairs (getting objects tagged with a specific string, please check out NSDictionary, or it's mutable subclass - NSMutableDictinary

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html

NSDictionary *newDictionary = @{@"Active" : self.someView};
NSString *activeView = myView[@"Active"];
Michael Voznesensky
  • 1,612
  • 12
  • 15
1

NSArrays don't have keys, just values, stored at numeric indices. You retrieve items by calling objectAtIndex and providing a number between 0 and count - 1. Perhaps you would be better off using an NSDictionary?

w0mbat
  • 2,430
  • 1
  • 15
  • 16
0

Your array is incredibly confusing, but you're looking for an 'Active' key, where there is none. Try 'appActive' : but i really have no idea what you are trying to achieve..

If you are, and correct me if I'm mistaken, a complete novice at programming, perhaps you shouldn't be using KVC and learn how to use NSArrays and NSDictionaries.

Rambatino
  • 4,716
  • 1
  • 33
  • 56