Accessing a value from an array of objects

I have two arrays, Namely

NMutableArray* first; NMutableArray* second; 

Now I copy the first object to the second array, for example

 for (int i=0;i<first.count; i++) { [second addObject:[first objectAtIndex:i]; } 

This is normal. I do not know how to access the value of the first array. I tried like this:

 [second addObject:[[first objectAtIndex:i]name]]; 

I want to get the value of the name that is in the first object of the first array. I tried using the above line, it shows some warning. Please help me

+8
ios iphone cocoa-touch cocoa foundation
source share
3 answers

Assuming you started with an array like this:

 NSArray *array1 = @[@{@name : @"Fred"}, @{@name : @"Bill"}]; 

You can create a second array that contains the value of this property of each element of the first array as follows:

 NSArray *array2 = [array1 valueForKey:@"name"]; 

If you then registered a second array ...

 NSLog(@"%@", array2); 

... the result will be

 2012-04-18 16:26:11.226 ExampleRunner[23320:707] ( Fred, Bill ) 

EDIT

Note that this will work regardless of whether the objects in the first array are NSDictionary instances, as shown in the above example, or instances of a class or classes that have a name property or an instance variable (or _name an instance variable, for that matter ) For more information on how and why this works, see the documentation for the unofficial NSKeyValueCoding protocol:

http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Reference/Foundation/Protocols/NSKeyValueCoding_Protocol/Reference/Reference.html

+7
source share

The brackets are currently in the wrong place:

 [second addObject:[[first objectAtIndex:i] name]]; 
+3
source share

Updated answer:

Again, I think you should split the material into a simple line-breaker:

 for (id theObject in first) { // without an actual type, I still think the compiler might // throw a warning on this next line of code; // but maybe RJR III is correct and it won't warn. // I didn't check. NSString * nameOfObject = [theObject name]; if(nameOfObject) { [second addObject:nameOfObject]; } } 

Please note that here I will also check for errors (i.e. make sure the name is not zero).

Original answer:

You get a warning because the compiler does not know which user object is retrieved from your call to " [first objectAtIndex: i] ". In other words, it does not know which object you are trying to get " name ".

Copy it to the desired type, and you will get rid of the warning.

Or even better, divide this line into several lines at once into two or three lines of code and make the code more understandable in this process.

+1
source share

All Articles