extracting data from an array of arrays - objective-c

I have the following code:
NSString *movies = [[NSString alloc] initWithData:webData7 encoding:NSUTF8StringEncoding];
NSLog(#"movies: %#", movies);
array_webdata = [parsedata objectWithString:movies error:nil];
userMovies = [array_webdata valueForKey:#"movies"];
NSLog(#"userMovies: %#", userMovies);
NSMutableArray *arrayCodes = [userMovies valueForKey:#"rtid"];
NSLog(#"arrayCodes: %#", arrayCodes);
In first line I save in movies the following:
movies:
{"movies":[["rtid","770672122"],["rtid","771268706"],["rtid","771240265"],["rtid","9377"]]}
with: userMovies = [array_webdata valueForKey:#"movies"]; I store in userMovies:
userMovies: (
rtid,
770672122
),
(
rtid,
771268706
),
(
rtid,
771240265
),
(
rtid,
9377
)
From here I want to extract the numbers to create another array like :
codes: (770672122, 771268706, 771240265, 9377)
But with following line, the execution crashes:
NSMutableArray *arrayCodes = [userMovies valueForKey:#"rtid"];
The error is EXC_BAD_ACCESS. On Debug Area shows no errors
Do you know what is wrong?
Thanks!
I have edited the question to make it more understandable

The code you have is clearly not going to work because you are assigning a number (or int, or some type) to a mutable array. You can't do that. You need to ADD them to the array since they will be contained IN THE ARRAY, those numbers ARE NOT arrays...
How are you getting it from JSON? Your array is probably an array of NSDictionary's so you'll want to do something like:
for (NSDictionary *aDictionary in userMovies)
{
[arrayCodes addObject: [aDictionary valueForKey:#"rtid"]];
}
You need to start by finding out what's in your array. Do:
NSLog(#"My array contains %#'s", [[userMovies valueForKey:#"rtid"] class]);
From there, if you get NSDictionary use the code above, and if you get an array, you'll have to loop through the array like:
for (NSArray *anArray in userMovies)
{
[arrayCodes addObject: [anArray objectAtIndex:1]];
}

SOLVED!
I have deleted my last two lines of code:
NSMutableArray *arrayCodes = [userMovies valueForKey:#"rtid"];
NSLog(#"arrayCodes: %#", arrayCodes);
and added the following
NSMutableArray *moviesCodes = [[NSMutableArray alloc] init];
for (int counter = 0; counter<[userMovies count]; counter++){
[moviesCodes addObject:[[userMovies objectAtIndex:counter] objectAtIndex:1]];
}
With this I have stored all the ids in the array called moviesCodes. The problem was that userMovies is an array of arrays

Related

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]);

Filter NSNumber Objects in NSMutableArray Without NSPredicate?

I feel like I have a unique problem. This problem stems from parsing a COLLADA XML file. I am filtering by whitespace in the element of the file, and it's working fine, except when I dump that to an NSArray, I get a bunch of junk zero values before I hit the actual points I am trying to isolate.
My question is… If my NSMutableArray has a bunch of NSNumber values, and I want to filter out all zero values, how can I do this?
I thought I could do something like:
NSNumber * newNumber;
NSMutableArray * newArray = [[NSMutableArray alloc] init];
for(oldNumber in oldMutableArray)
{
if(oldNumber != 0)
{
[newArray addObject: oldNumber];
}
}
This does not work, however. :)
Your main issue here is that != 0 is really checking for nil values, not if the NSNumber is equal to 0.
You should be able to just do this:
[allXMLObjects removeObject:#(0)];
This will remove all occurrences of NSNumbers that have a numerical value of 0.
Add oldNumber, not newNumber. newNumber was nil
NSMutableArray * newarray = [[NSMutableArray alloc] init];
for(oldNumber in oldmutablearray)
{
if(oldnumbervalues != 0)
{
[newarray addObject: oldNumber]; //Add old number, not newNumber. newNumber was nil
}
}

Flatten an NSArray

I have an array like this:
array: (
(
"http://aaa/product/8_1371121323.png",
"http://aaa/product/14_1371123271.png"
),
(
"http://aaa/product/9_1371121377.png"
)
)
and I have to create another array from that one like this
array: (
"http://aaa/product/8_1371121323.png",
"http://aaa/product/14_1371123271.png",
"http://aaa/product/9_1371121377.png"
)
How can I do that? Is it possible to combine all the objects and separate them using some string?
It can be done in a single line if you like key-value coding (KVC). The #unionOfArrays collection operator does exactly what you are looking for.
You may have encountered KVC before in predicates, bindings and similar places, but it can also be called in normal Objective-C code like this:
NSArray *flatArray = [array valueForKeyPath: #"#unionOfArrays.self"];
There are other collection operators in KVC, all prefixed with an # sign, as discussed here.
Sample Code :
NSMutableArray *mainArray = [[NSMutableArray alloc] init];
for (int i = 0; i < bigArray.count ; i++)
{
[mainArray addObjectsFromArray:[bigArray objectAtIndex:i]];
}
NSLog(#"mainArray :: %#",mainArray);
Sample code:
NSArray* arrays = #(#(#"http://aaa/product/8_1371121323.png",#"http://aaa/product/14_1371123271.png"),#(#"http://aaa/product/9_1371121377.png"));
NSMutableArray* flatArray = [NSMutableArray array];
for (NSArray* innerArray in arrays) {
[flatArray addObjectsFromArray:innerArray];
}
NSLog(#"%#",[flatArray componentsJoinedByString:#","]);
NSMutableArray *arr1 = [NSMutableArray arrayWithArray:[initialArray objectAtIndex:0]];
[arr1 addObjectsFromArray:[initialArray objectAtIndex:1]];
Now arr1 contains all the objects

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]);