NSMutableArray with multiple properties [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a rather large NSMutableArray with class files. The array has multiple properties like so:
[Element elementsName:#"Lithium" elementsNumber:#"3"],
[Element elementsName:#"Beryllium" elementsNumber:#"4"],
[Element elementsName:#"Boron" elementsNumber:#"5"],
[Element elementsName:#"Carbon" elementsNumber:#"6"],
[Element elementsName:#"Nitrogen" elementsNumber:#"7"],
[Element elementsName:#"Oxygen" elementsNumber:#"8"],
[Element elementsName:#"Fluorine" elementsNumber:#"9"],
[Element elementsName:#"Neon" elementsNumber:#"10"],
I need to be able to access the elementsName and the elementsNumber separately.
Would anybody know how to do this, and is it possible? Thanks! (More code below!)
Element.h (class for the array)
#interface Element : NSObject
{
NSString *name;
NSString *number;
}
#property(nonatomic, copy)NSString *name;
#property(nonatomic, copy)NSString *number;
+(id)elementsName:(NSString *)name elementsNumber:(NSString *)number;
and Element.m
#import "Element.h"
#implementation Element;
#synthesize number;
#synthesize name;
+(id)elementsName:(NSString *)name elementsNumber:(NSString *)number
{
Element *newElement = [[self alloc] init];
newElement.name = name;
newElement.number = number;
return newElement;
}
#end

You could try something like this:
for(int i = 0; i<elementArray.count; i++)
{
NSString *name = ((Element*)[elementArray objectAtIndex:i]).name;
NSString *number = ((Element*)[elementArray objectAtIndex:i]).number;
}

Is this what you are looking for? :
// returns an array of all numbers
NSArray *numbers = [elementArray valueForKey:#"number"];
// returns an array of all names
NSArray *names = [elementArray valueForKey:#"name"];
This is called KVC (Key-Value Coding) and uses strings to access an object's property. This example goes through all of the elements in the array and asks for its number or name property, then returns the result as an array.
This could also be achieved with a for-loop. I am mainly including this to give you an idea of what is happening:
NSMutableArray *names = [NSMutableArray array];
NSMutableArray *numbers = [NSMutableArray array];
for (Element *e in elementsArray) {
[names addObject:e.name];
[numbers addObject:e.number];
}
Obviously this would work as well, but why not use valueForKey: when it is designed for this?

You can use NSDictionary instead.
NSArray *arrOfDic=#[#{#"elementsName":#"Lithium",#"elementsNumber":#"3"},
#{#"elementsName":#"Beryllium",#"elementsNumber":#"4"},
#{#"elementsName":#"Boron",#"elementsNumber":#"5"},
#{#"elementsName":#"Carbon",#"elementsNumber":#"6"},
#{#"elementsName":#"Nitrogen",#"elementsNumber":#"7"}];
NSLog(#"dic is %#",arrOfDic);
Get your elements and their number as
NSLog(#"FirstObject is Element = %# Element No = %#",arrOfDic[0][#"elementsName"],arrOfDic[0][#"elementsNumber"]);
NSLog(#"SecondObject is Element = %# Element No = %#",arrOfDic[1][#"elementsName"],arrOfDic[1][#"elementsNumber"]);
And whats wrong with your file it is working fine.
NSMutableArray *mArray=[[NSMutableArray alloc] init];
[mArray addObject:[Element elementsName:#"Lithium" elementsNumber:#"3"]];
[mArray addObject:[Element elementsName:#"Beryllium" elementsNumber:#"5"]];
[mArray addObject:[Element elementsName:#"Boron" elementsNumber:#"6"]];
Element *element=(Element*)[mArray objectAtIndex:0];
NSLog(#"My first element is name = %# ,number = %#",element.name,element.number);
output---
My first element is name = Lithium ,number = 3

Related

how to store an NSString variable in an NSMutable array in objective c [duplicate]

This question already has answers here:
Having trouble adding objects to NSMutableArray in Objective C
(2 answers)
Closed 7 years ago.
I am trying to store an NSString variable in an NSMutableArray:
#property(weak,nonatomic) NSMutableArray * stringLines;
//----
NSString * string=#"hello";
[self.stringLines addObject: string];
int i=0;
for (id obj in _stringLines){
NSLog(#"printing labels: index %x word %#",i, obj);
i++;
}
but when I try to print the mutable array, it shows me null values. I don't want to assign the text directly to the array, it has to be through the variable string.
Did you initialize self.stringLines? It may be nil. Try initializing to an empty array, then add the strings.
#property(weak,nonatomic) NSMutableArray * stringLines;
//----
self.stringLines = [NSMutableArray array];
NSString *string = #"hello";
[self.stringLines addObject:string];
NSLog(#"Print strings array: %#", self.stringLines);
That's because you have not allocated the array object. So if you add anything to a nil object you won't find anything inside it. Use this code
//----
self.stringLines = [[NSMutableArray alloc] init];
NSString * string=#"hello";
[self.stringLines addObject: string];
you can also initialize the array by adding the object with literal, so you need only 1 line of code instead of 3:
self.stringLines = #[#"hello"];

iOS: sorting an NSArray of core data objects [duplicate]

This question already has answers here:
How do I sort an NSMutableArray with custom objects in it?
(27 answers)
Closed 8 years ago.
I have a NSArray with core data entities called:
"Struct"
thy have an attribute called "value" that can be a double
Struct *struct = [array objectAtIndex:0];
double val = [struct value];
I have to sorting this array by this value but I don't understand what's the way to do it, because I have not a key to access to the object.
Do you have any suggests?
NSMutableArray *sortedArray;
sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSNumber *s1 = #([(Struct *)a value]);
NSNumber *s2 = #([(Struct *)b value]);
return [s1 compare:s2];
}];

Remove Duplicate Objects From NSMutableArray object property? [duplicate]

This question already has answers here:
How to remove all objects with the same property value but one in NSMutableArray
(3 answers)
Closed 9 years ago.
I have one NSObject with properties as following
#property (nonatomic, retain) NSString * destinationid;
#property (nonatomic, retain) NSString * destinationname;
#property (nonatomic, retain) NSString * assetid;
#property (nonatomic, retain) NSString * assetname;
#property (nonatomic, retain) NSString * assetdescription;
Here, I save this in NSMutableArray.
The data which I get from server contains same DestinationName, but different other properties.
I want to check, if same name of Object is already added to NSMutableArray, don't add it again.
I tried to user innner loops but no use :(
Thanks
Here's one solution:
NSArray *originalArray = ... // original array of objects with duplicates
NSMutableArray *uniqueArray = [NSMutableArray array];
NSMutableSet *names = [NSMutableSet set];
for (id obj in originalArray) {
NSString *destinationName = [obj destinationname];
if (![names containsObject:destinationName]) {
[uniqueArray addObject:obj];
[names addObject:destinationName];
}
}
One way to do it is to create a new array that only contains the destination names from your other array, and check if the name from your server is contained there:
NSArray *names = [self.mut valueForKey:#"destinationname"];
if (![names containsObject:destName]) {
[self.mut addObject:newObjectFromServer];
}
mut is the name of my mutable array, and destName is the destination name in the object your getting from the server.
This function should do the job:
BOOL contains(id object, NSMutableArray *array)
{
for (id array in yourArray)
if ([object.destinationname isEqualToString:yourObject.destinationname])
return YES;
return NO;
}
Usage example:
if (!contains(object, array))
[array addObject:object];

populating NSMutableArray not working

Hi I have an instance variable NSMutable Array.
I declare it as such
#property (nonatomic, assign) NSMutableArray *list;
In viewDidLoad I instantiate it.
self.list = [NSMutableArray array];
I then make a string consisting of the text of text fields and add it to the array.
NSString * lines = [NSString stringWithFormat:#"%#,%#,%#,%#,%#", [self.crabText text], [self.trawlText text], [self.trapText text], [self.vesselText text], [self.lengthText text]];
[self.list addObject:lines];
This is apart of a function which will keep on adding new values of the text fields into the array.
I display the contents of the array with
int i;
int count;
for (i = 0, count = [self.list count]; i < count; i = i + 1)
{
NSString *element = [self.list objectAtIndex:i];
NSLog(#"The element at index %d in the array is: %#", i, element); // just replace the %# by %d
}
However, the app crashes when I try to print the contents of the array and I get
EXC_BAD_ACCESS_CODE
Any ideas?
Thanks!
Replace your declaration like this :
#property (nonatomic, strong) NSMutableArray *list; // strong and not assign
Initialize your array in your viewDidLoad :
self.list = [NSMutableArray array];
and add one by one your string :
[self.list addObject:self.crabText.text];
[self.list addObject:self.trawlText.text];
....
Next, modify your for loop :
for (int i = 0, i < self.list.count, i++)
{
NSLog(#"The element at index %d in the array is: %#", i, [self.list objectAtIndex:i]);
}
Another way to do this would be to declare the array this way in your header file
#interface yourViewController : UIViewController
{
NSMutableArray* list;
}
#end
Then in the ViewDidLoad
list = [[NSMutableArray alloc] init];
Everything else can be done just as Jordan said. Though I'm not sure if there is a difference in performance between either implementation.

NSMutableArray removeObjectAtIndex causing unexpected SIGABRT

I have looked at numerous posts which state various ways in which to remove an object from an array correctly, but I am not sure which method is best to use in my instance. I am loading a dictionary from a plist, this dictionary contains numerous arrays, and these arrays contain another dictionary. So I have 3 storage devices setup, 1 to hold the overall dictionary, another for an array, and finally a dictionary to hold the object from the array:
Header:
NSMutableDictionary *questionsDictionary;
NSMutableArray *questionsArray;
NSDictionary *currentQuestion;
#property (nonatomic, retain) NSMutableDictionary *questionsDictionary;
#property (nonatomic, retain) NSMutableArray *questionsArray;
#property (nonatomic, retain) NSDictionary *currentQuestion;
So my first question is to do with the above, are (nonatomic, retain) the right things to use for the following code.
Next I load in my dictionary from the plist:
.m:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"MultipleChoice.plist"];
self.questionsDictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];
I then setup my question array based upon type based upon my question type:
- (void)setupQuestionType : (NSString *)qType
{
if ([self.questionsDictionary objectForKey:qType])
{
self.questionsArray = [self.questionsDictionary objectForKey:qType];
[self pickRandomQuestion];
}
}
Finally (this is where I get the error), I want to grab the a question at random from this question category:
// Pick a random question number based upon amount of questions
int randomQuestionNum = [[NSNumber numberWithInt:(arc4random() % [self.questionsArray count])] intValue];
// Grab the dictionary entry for that question
currentQuestion = [self.questionsArray objectAtIndex:randomQuestionNum];
// Remove the question from the available questions
[self.questionsArray removeObjectAtIndex:randomQuestionNum]; (Error here)
// Set the question text
self.question.text = [currentQuestion objectForKey:kQuestionkey];
Now if I comment out the removeObjectAtIndex line then the code runs fine, and my question is displayed on the screen. This leads me to believe that it isn't a null pointer. So the logical answer points to the fact that self.questionsArray isn't a NSMutableArray. So I tried the following when setting the array:
- (void)setupQuestionType : (NSString *)qType
{
if ([self.questionsDictionary objectForKey:qType])
{
NSMutableArray *temp = (NSMutableArray *)[self.questionsDictionary objectForKey:qType];
self.questionsArray = (NSMutableArray *)temp;
[self pickRandomQuestion];
}
}
Purely to see if I could type_cast it but the error still occurs. Can anyone shed some light on what I'm doing wrong, or the best approach to take?
Don't typecast NSArray to NSMutableArray. Instead:
NSArray *temp = [self.questionsDictionary objectForKey:qType];
self.questionsArray = [NSMutableArray arrayWithArray:temp];
// code not tested.

Resources