object array to NSMutable array [duplicate] - objective-c

This question already has an answer here:
Getting an array of a property from an object array
(1 answer)
Closed 7 years ago.
I have an array of Objects.Object contains three values, id,name,value.I want to parse name from this object array and want to create a different array of names only....Can anyone help Plz.....
int i;
NSInteger *namesCount=[eCategories count]; //eCategories is an object array
SubCategories *subCategoriesList=[[SubCategories alloc] init];
//SubCategories is a NSObject class containing cat_name,cat_id,cat_value.
NSMutableArray *nameArray=[[NSMutableArray alloc]init];
for(i=0;i<namesCount;i++)
{
subCategoriesList=[eCategories objectAtIndex:i];
nameArray=subCategoriesList.cat_name;
}

NSArray has a method -valueForKey: which does exactly what you want in one message
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.
NSArray* nameArray = [eCategories valueForKey: #"cat_name"];

How about
[objects valueForKeyPath: #"#distinctUnionOfArrays.name"]
Unless, of course, the objects inside the array are not NSDictionaries with "name" as the key for the names. You're not telling us enough.

int i;
NSInteger *namesCount=[eCategories count]; //eCategories is an object array
SubCategories *subCategoriesList=[[SubCategories alloc] init];
//SubCategories is a NSObject class containing cat_name,cat_id,cat_value.
NSMutableArray *nameArray=[[NSMutableArray alloc]init];
for(i=0;i
[nameArray addobject:subCategoriesList.cat_name];
}

Related

access object properties from a multidimensional array in objective-c

I am new to Objective-C programming and I am trying to access object properties from a 2 dimensional array.
First I created two arrays, each of those arrays contains objects, then I made a 2 dimensional array that contains those arrays of objects by using NSMutableArray
NSMutableArray *team1 = [[NSMutableArray alloc] init];
[team1 addObject:tank1];
[team1 addObject:btr1];
[team1 addObject:ambulance1];
NSMutableArray *team2 = [[NSMutableArray alloc] init];
[team2 addObject:tank2];
[team2 addObject:btr2];
[team2 addObject:ambulance2];
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:2];
[array addObject:team1];
[array addObject:team2];
What I want to do now is to access the properties of these objects by referring them from my 2d array and print them by using NSLog. Is this possible?
Please excuse me my question looks complicated, this is something new for me.
Use the above reference code to access the object like this.
1. To access btr 1
index for this will be : item 0, object 1 for array so can access by this code.
[[array objectAtIndex:0] objectAtIndex:1]
2. To access ambulance2
index for this will be : item 0, object 1 for array so can access by this code.
[[array objectAtIndex:1] objectAtIndex:2]
You can print them with same code given here as
NSlog(Item at object: %d index of 'array' and item in 'array' at index : %d is == %#,outerarray(array) index, innerarray(item array) index, [[array objectAtIndex:outerarrayindex] objectAtIndex:innerarrayindex]);
Or simply NSlog(#"%#",[[array objectAtIndex:outerarrayindex] objectAtIndex:innerarrayindex]);

Filtering a NSMutableArray and returning only numbers

I have a NSMutableArray called myMutableArray inside him, I have the following values:
('R$ 118.98','AE 12.00 er','R$ 456.99')
What I would do, is find a way to filter the information contained within this array, thus making it returns only numeric characters, for example:
('118.98','12.00','456.99')
I have a simple code who get the lines inside an array:
for(int x=0; x<[myMutableArray count]; x++){
myMutableArray[x];//We need to find a way to filter and update this informations to only store numbers.
}
What the code I can put in my code to filter the information inside my array to only storing numbers?
Try:
//create a new mutable array to store the modified values
NSMutableArray *arrFinal = [[NSMutableArray alloc] init];
//fast-enumerate within myMutableArray
for (NSString *strCurrent in myMutableArray) {
NSString *strModified = [strCurrent stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
[arrFinal addObject:strModified];
}
NSLog(#"%#",[arrFinal description]);

Create Instance variables at runtime

I want to create instance variables dynamically at runtime, and I want to add these variables to a category. The number of the instance variables may change based on the configuration/properties file which I am using for defining them.
Any ideas??
Use Associative References - this is tricky, but that is the mechanism invented specifically for your use case.
Here is an example from the link above: first, you define a reference and add it to your object using objc_setAssociatedObject; then you can retrieve the value back by calling objc_getAssociatedObject.
static char overviewKey;
NSArray *array = [[NSArray alloc] initWithObjects:# "One", #"Two", #"Three", nil];
NSString *overview = [[NSString alloc] initWithFormat:#"%#", #"First three numbers"];
objc_setAssociatedObject (
array,
&overviewKey,
overview,
OBJC_ASSOCIATION_RETAIN
);
[overview release];
NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);
NSLog(#"associatedObject: %#", associatedObject);
objc_setAssociatedObject (
array,
&overviewKey,
nil,
OBJC_ASSOCIATION_ASSIGN
);
[array release];
I'd be inclined to just use a NSMutableDictionary (see NSMutableDictionary Class Reference). Thus, you would have an ivar:
NSMutableDictionary *dictionary;
You'd then initialize it:
dictionary = [NSMutableDictionary dictionary];
You can then save values to it dynamically in code, e.g.:
dictionary[#"name"] = #"Rob";
dictionary[#"age"] = #29;
// etc.
Or, if you are reading from a file and don't know what the names of the keys are going to be, you can do this programmatically, e.g.:
NSString *key = ... // your app will read the name of the field from the text file
id value = ... // your app will read the value of the field from the text file
dictionary[key] = value; // this saves that value for that key in the dictionary
And if you're using an older version of Xcode (before 4.5), the syntax is:
[dictionary setObject:value forKey:key];
Depends on exactly what you want to do, the question is vague but if you want to have several objects or several integers or so on, arrays are the way to go. Say you have a plist with a list of 100 numbers. You can do something sort of like this:
NSArray * array = [NSArray arrayWithContentsOfFile:filePath];
// filePath is the path to the plist file with all of the numbers stored in it as an array
That will give you an array of NSNumbers, you can then turn that into an array of just ints if you want like this;
int intArray [[array count]];
for (int i = 0; i < [array count]; i++) {
intArray[i] = [((NSNumber *)[array objectAtIndex:i]) intValue];
}
Whenever you want to get an integer from a certain position, lets say you want to look at the 5th integer, you would do this:
int myNewInt = intArray[4];
// intArray[0] is the first position so [4] would be the fifth
Just look into using a plist for pulling data, it will them be really easy to create arrays of custom objects or variables in your code by parsing the plist.

Load an element value of an array to another array Xcode Objective-C

Here I am getting the cityName1 with the city names like Piscataway, Iselin, Broklyn etc fetched from the tgpList1 array and I need to put the values into an array called item5.
There are 133 records fetched by the above iteration. The following code stores only the last record's cityName1 and not the entire list of city names though inside the loop.
I tried many ways but I am missing something.
tgpList1 is an array.
tgpDAO is an NSObject with two objects NSString *airportCode and NSString *cityName
NSArray *item5 = [[NSArray alloc]init];
for (int currentIndex=0; currentIndex<[tgpList1 count]; currentIndex++)
{
tgpDAO *tgpTable = (tgpDAO *)[self.tgpList1 objectAtIndex:currentIndex];
NSLog(#"The array values are %#",tgpList1);
NSString *cityName1 = tgpTable.cityName;
item5 =[NSArray arrayWithObjects:cityName1, nil];
}
Use mutable array.
{
NSMutableArray *item5 = [[NSMutableArray alloc]initWithArray:nil];
for (int currentIndex=0; currentIndex<[tgpList1 count]; currentIndex++) {
tgpDAO *tgpTable = (tgpDAO *)[self.tgpList1 objectAtIndex:currentIndex];
NSLog(#"The array values are %#",tgpList1);
NSString *cityName1 = tgpTable.cityName;
[item5 addObject:cityName1];
}
}
Instead of
item5 =[NSArray arrayWithObjects:cityName1, nil];
use
[item5 addObject:cityName1];
There are more ways of achieving that. However, this is the one that is designed for that purpose and the most "readable" from my pont of view.
If you need to clear the contents of item5 before then call
[item5 removeAllObjects];
right before the for loop.
What you were doing: arrayWithObjects allways creates a new array that ist made of the objects that are passed to it as aguments. If you do not use ARC, then you would create some serious memory leak with your code because arrayWithObjects creates and retains an object on every loop and on the next loop all references to the array object, that was just created, are lost without being released. If you do ARC then you do not have to worry about in this case.
NSMutableArray *myCities = [NSMutableArray arrayWithCapacity:2]; // will grow if needed.
for( some loop conditions )
{
NSString* someCity = getCity();
[myCities addObject:someCity];
}
NSLog(#"number of cities in array: %#",[myCities count]);

How to create a 2D NSArray or NSMutableArray in objective C?

I want to ask about the objective C question. I want to create a 2D NSArray or NSMutableArray in objective C. What should I do? The object stored in the array is NSString *. Thank you very mcuh.
This is certainly possible, but i think it's worthy to note that NSArrays can only hold objects, not primitive types.
The way to get around this is to use the primitive wrapper type NSNumber.
NSMutableArray *outer = [[NSMutableArray alloc] init];
NSMutableArray *inner = [[NSMutableArray alloc] init];
[inner addObject:[NSNumber numberWithInt:someInt]];
[outer addObject:inner];
[inner release];
//do something with outer here...
//clean up
[outer release];
Try NSMutableDictionary with NSNumbers as keys and arrays as objects. One dimension will be the keys, the other one will be the objects.
To create the specific "2D array"
NSMutableDictionary *twoDArray = [NSMutableDictionary dictionary];
for (int i = 0; i < 10; i++){
[twoDArray setObject:arrayOfStrings forKey:[NSNumber numberWithInt:i]];
}
To pull the data
NSString *string = [[twoDArray objectForKey:[NSNumber numberWithInt:3]] objectAtIndex:5];
//will pull string from row 3 column 5 -> as an example
Edited to make my answer more applicable to the question. Initially I didn't notice that you were looking for a 2D array. If you know how many by how many you need up front you can interleave the data and have a stride. I know that there are probably other (more objective standard) ways of having arrays inside of an array but to me that gets confusing. An array inside of an array is not a 2 dimensional array. It's just a second dimension in ONE of the objects. You'd have to add an array to each object, and that's not what I think of as a 2 dimensional array. Right or wrong I usually do things in a way that makes sense to me.
So lets say you need a 6x6 array:
int arrayStride=6;
int arrayDepth=6;
NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:arrayStride*arrayDepth];
I prefer to initialize the array by filling it up with objects;
for(int i=0; i<arrayStride*arrayDepth; i++) [newArray addObject #"whatever"];
Then after that you can access objects by firstDim + secondDim*6
int firstDim = 4;
int secondDim = 2;
NSString *nextString = [newArray objectAtIndex:firstDim+secondDim*6];