This question already has answers here:
Getting an NSArray of a single attribute from an NSArray
(3 answers)
Closed 9 years ago.
I have the following issue, I need to get an array of values from an array of custom Objects. Is there a method for doing this without iterating the principal array, let me graphic it a little bit.
NSArray *principalArray = #[
customObject1,customObject2,customObject3,....customObject(n)
];
This customObject instances have a properties lets say id,name,lastname.
I want to get an NSArray with the value of name from the principalArray
Thanks for your help.
EDIT:
As somebody pointed out in comments: its a duplicate of existing SO question: Getting an NSArray of a single attribute from an NSArray
There is a method for NSArray - valueForKey - with key being an attribute of your first array. This method returns you an NSArray from an NSArray.
In your case you can do the following:
NSArray *nameArray = [principalArray valueForKey:#"name"];
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am pretty new to objective-c, and I've tried searching around for possible answers - and I've had little to no luck.
What I want to do is store multiple names and numbers, and retrieve these when needed. It's basically for storing scores.
I tried using an NSDictionary, which contained keys and objects, where the keys were the names and object was the score. However, I am not sure how I can retrieve the number and add something onto it, as I am getting an incompatible pointer warning and the application breaks.
Is there a better approach to store user details and scores and retrieve them and update them when needed?
The NSDictionary seems like a okay start, since this searches more efficiently than an array. Maybe you get trapped by NSNumber != int. (NSNumbers are objects, no primitives.) Check the docs and see, if they help you.
A simple example, assuming dict is actually a NSMutableDictionary,
notice the # when setting the new value:
int currentPoints = [[dict objectForKey:#"name"] intValue];
int newPoints = currentPoints + 5;
[dict setObject:#(newPoints) forKey:#"name"];
Either create a mutable array of mutable dictionaries, or a mutable array of custom UserInfo objects.
Something simple like this would work:
#interface Userinfo: NSObject
#property (nonatomic, strong) NSString *name
#property (nonatomic, assign) int score
#end
You can store data like this
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:#"player1" forKey:#"user_name"];
[dictionary setObject:#"10" forKey:#"user_score"];
[userList addObject:dictionary];
you can retrieve as mentioned below :
NSDictionary *dictionary = [[NSDictionary alloc] initWithDictionary:[userList objectAtIndex:0]];
lblName.text = [dictionary valueForKey:#"user_name"];
lblScore.text = [dictionary valueForKey:#"user_score"];
I think this will work for you.
This question already has answers here:
insert object in an NSMutableArray saved with NSUserDefaults
(6 answers)
Closed 8 years ago.
I have an NSMutableArray and I am trying to use the insertObjectAtIndex method, but it does not work. It seems to think I am trying to do something mutable with an immutable array..... but I am using an NS ..... MUTABLE.... Array. So what an earth could be wrong??
Here is my code:
if ([dataArray count] == 0) {
// Initialise the audio arrays.
dataArray = [[NSMutableArray alloc] init];
// Now add the data to the array.
[dataArray addObject:#"test 1"];
}
else {
[dataArray insertObject:#"test 2" atIndex:0];
}
NSLog(#"d in: %#", dataArray);
The dataArray is defined in the header file like so:
NSMutableArray *dataArray;
Thanks for your time, Dan.
Oh sorry everyone, I just figured out what was wrong. I did edit the code in my question a bit, but basically what I am actually populating the NSMutableArray with is an array stored in an NSUserDefault, (which of course returns immutable arrays only).
So even though I am using an NSMutableArray to store the data, its still has immutable contents. In order to over come this, I ended up using "mutableCopy" iOS method to get a mutable copy of the contents of the NSUserDefaults array.
This question already has an answer here:
Getting an array of a property from an object array
(1 answer)
Closed 7 years ago.
Is it possible to take an NSArray of custom objects and get an array of values from the objects in the array?
So if i had a class
#interface CustomObject : NSObject
{
NSNumber *number;
NSString *studentName;
}
And an NSArray of n+ CustomObject
Is it possible to take the Array and get an NSArray of the just the NSNumber number values?
So
NSArray : [
NSNumber,
NSNumber,
NSNumber
]
Yes, you can do this with the KVO method valueForKey:
NSArray *numbers = [myArray valueForKey:#"number"];
You can check out the method in the NSArray class reference.
Yes you can do that. You can use valueForKey: KVC method for getting the extracting the number from the object contained in the array.
NSArray *allNumbers = [yourArray valueForKey:#"number"];
You can read more about valueForKey: in NSKeyValueCoding Class Reference
This question already has answers here:
Having trouble adding objects to NSMutableArray in Objective C
(2 answers)
Closed 8 years ago.
I want to add a first an last name to one index of a mutable array.
I'm loading a first and last name from the AdressBook API and I want the first and last name in an array, so I can display that later to the user.
Currently, I can log the first an last name, but when I try to add these to an array, the array stays null.
This is the code I'm using:
[_names addObject:[NSString stringWithFormat:#"%# %#", firstName, lastName]];
NSLog(#"%#", _names); //prints 'null'
NSLog(#"Name:%# %#", firstName, lastName);//prints 'John Appleseed'
Why isn't my array being updated?
Have you made sure you initiated the array properly using _names = [[NSMutableArray alloc] init]? You cannot add objects into an uninitialized array.
This question already has answers here:
How do I sort an NSMutableArray with custom objects in it?
(27 answers)
Closed 9 years ago.
Hopefully someone can help.
I'm adding multiple objects to a NSMutableArray and I need to sort the order based on the first element which will always be a number.
However I'm unsure how to do this?
For example:
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray *object = [NSArray arrayWithObjects: #"1",#"Test",#"Test"];
[array addObject:object];
Thanks
If your array always contains other arrays, and the first element of the innermost array is always a string containing a number, you could use the NSMutableArray method sortUsingComparator to sort your array:
[array sortUsingComparator: ^(NSArray* obj1, NSArray* obj2)
{
int value1 = [obj1[0] integerValue];
int value2 = [obj2[0] integerValue];
if (value1==value2)
return NSOrderedSame;
else if (value1 < value2)
return NSOrderedAscending;
else
return NSOrderedDescending;
}
];
In the sortUsingComparator family of methods, you supply a block of code that the sort method uses to compare pairs of objects in your array. The block uses the standard typedef NSComparator, which takes 2 objects as parameters and returns a value of type NSComparisonResult.
The code above will probably crash if all the objects in your array are not arrays of strings. (Actually it would work if the first element of each component array was an NSNumber, since NSNumber also responds to the integerValue message.)
If you are going to use this code in a very controlled environment where you can be sure that the data you are sorting is well-formed, it should work as written. If there is any chance that the objects in the array would be of a different type, or be empty, or that their first element would not respond to the integerValue messages, then you should add error checking code.
If you sort your array alphanumerically, the object #"1" will appear before any words. Keep in mind though that #"1" in your code above is a string, not a number.
As to how to sort an array, look into [NSArray sortedArrayUsingComparator:] and similar methods.