Reputation: 1588
I am having two arrays, Namely
NMutableArray* first;
NMutableArray* second;
Now I am copying first object to the second array like
for (int i=0;i<first.count; i++)
{
[second addObject:[first objectAtIndex:i];
}
This is ok. I don't 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 name value which is in the first object of first array. I tried using the above line, it is showing some warning. Please help me
Upvotes: 8
Views: 1593
Reputation: 15617
Assuming you started with an array like this:
NSArray *array1 = @[@{@name : @"Fred"},
@{@name : @"Bill"}];
You could create a second array that contains the value of a given property of each element of the first array as follows:
NSArray *array2 = [array1 valueForKey:@"name"];
If you then logged the second array...
NSLog(@"%@", array2);
...the resulting output would 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 instances of NSDictionary
as shown in the example above, or instances of a class or classes that have a name
property or instance variable (or an _name
instance variable, for that matter). For more information on how and why this works, see the documentation for the NSKeyValueCoding
informal protocol:
Upvotes: 7
Reputation: 89569
Updated Answer:
Again, I think you should split stuff out into easy to parse lines of code:
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];
}
}
Notice that I do some error checking in here as well (i.e. making sure the name is not nil).
Original Answer:
You're getting a warning because the compiler doesn't know what kind of custom object is being fetched from your call to "[first objectAtIndex: i]
". In other words, it doesn't know what kind of object you're trying to get the "name
" of.
Cast it to the right type and you'll get rid of the warning.
Or even better, split that one line of multiple things happening at once into two or three lines of code and make your code more readable in the process.
Upvotes: 1
Reputation: 1138
The brackets are currently in the wrong place:
[second addObject:[[first objectAtIndex:i] name]];
Upvotes: 3