pasing complex string on iphone - iphone

i want to parse this string
appDelegate.gpsArray= "\n\n 21.318\n03.863\n\n\n 21.317\n03.864\n\n\n 11.316\n113.864\n\n\n"
so that i cant get value like
1) a[0]=21.318, a[1]=03.863,a[3]=11.317,a[4]=113.846....
or how to get this as 2d array like
2)
a[0,0]=21.318,103.863
a[1,1]=21.318,103.863
i did this but of no use
NSMutableArray *a1 = [[NSMutableArray alloc] init];
[a1 addObjectsFromArray:appDelegate.gpsArray ];
Kindly suggest how to use both ways like 1D and 2D

I'd solve your problem in this way:
NSArray *stringsArray = [appDelegate.gpsArray componentsSeparatedByString:"\n"];
NSMutableArray *result = [NSMutableArray array];
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
for (NSString *str in stringsArray ) {
if( ![str isEqualToString:#""] ) {
[result addObject:[f numberFromString:str]];
}
}
[f release];
Then you can convert the result array to two-dimensional array:
NSMutableArray *result2D = [NSMutableArray array];
for ( int i = 0; i < [result count] / 2; i++ ) {
NSMutableArray *innerArray = [[NSMutableArray alloc] init];
[innerArray addObject:[result objectAtIndex:2 * i]];
[innerArray addObject:[result objectAtIndex:2 * i + 1]];
[result2D addObject:innerArray];
[innerArray release];
}

Related

how to combine two mutable arrays values in single mutable array? [duplicate]

This question already has answers here:
How would I combine two arrays in Objective-C?
(2 answers)
Closed 9 years ago.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"json.... %#",json);
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(#"jsonObject=%#", jsonObject);
NSDictionary *checkArray=[json valueForKey:#"ND"];
NSArray *tel = [checkArray valueForKey:#"FN"];
testArray = [[NSMutableArray alloc]init];
testArray1 = [[NSMutableArray alloc]init];
newsarray = [[NSMutableArray alloc]init];
for (id photo in tel)
{
if (photo == [NSNull null])
{
NSString *test8;
test8 = #"empty";
[testArray addObject:test8];
}
else
{
// photo isn't null. It's an array
NSArray *innerPhotos = photo;
[testArray addObject:photo];
}
}
NSArray *tel1 = [checkArray valueForKey:#"LN"];
for (id photo1 in tel1)
{
if (photo1 == [NSNull null])
{
NSString *test8;
test8 = #"empty";
[testArray1 addObject:test8];
}
else
{
// photo isn't null. It's an array
//NSArray *innerPhotos1 = photo1;
[testArray1 addObject:photo1];
}
}
newsarray = [NSMutableArray arrayWithArray:[testArray arrayByAddingObjectsFromArray:testArray1]];
NSLog(#"testArray =%#",newsarray);
here i want to combine two array values "testArray" and "testArray1"
my mutablearray values are
testArray = aa, bb, cc, dd...
testArray1= xx, yy, zz, ss...
i would like to expect my output like
aa xx, bb yy, cc zz, dd ss
Try this:
for (int i=0;i<[testArray count];i++){
NSString *tmpObject=[NSString stringWithFormat:#"%# %#",
[testArray objectAtIndex:i],
[testArray1 objectAtIndex:i]];
[newArray addObject tmpObject];
tmpObject=nil;
}
you can do something like below..
NSMutableArray *aryFinal=[[NSMutableArray alloc]init];
int count = [testArray count]+[testArray1 count];
for(int i=0;i<count;i++)
{
if(i%2==0)
[aryFinal addobject:[testArray objectAtIndex:i]];
else
[aryFinal addobject:[testArray1 objectAtIndex:i]];
}
let me know it is working or not!!!
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:#"AA",#"BB",#"CC" nil];
NSArray *array2 = [NSArray arrayWithObjects:#"XX",#"YY",#"ZZ" nil];
for (int i=0; i<[array1 count];i++)
[array1 replaceObjectAtIndex:i
withObject:[NSString stringWithFormat:#"%# %#",
array1[i],
array2[i]]];
NSLog(#"%#",array1);
Output:
"AA XX","BB YY","CC ZZ"
To simply add two arrays:
[testArray setArray: testArray1];
But if you want desired result:
NSMutableArray *arrFinal=[[NSMutableArray alloc]init];
for(int i = 0; i < (testArray.count + testArray1.count); i++)
{
if(i%2 == 0)
[arrFinal addobject:[testArray objectAtIndex:i]];
else
[arrFinal addobject:[testArray1 objectAtIndex:i]];
}
Do not need to go for third array. You can use replaceObjectAtIndex method of NSMutableArray.
This way..
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:#"aa",#"bb", nil];
NSArray *array2 = [NSArray arrayWithObjects:#"xx",#"yy", nil];
for (int i=0; i<[array1 count];i++)
[array1 replaceObjectAtIndex:i withObject:[NSString stringWithFormat:#"%# %#",array1[i],array2[i]]];
for aa xx, bb yy, cc zz, dd ss output:
int i=-1;
for(int k =0;k<[testArray1 count];++k)
{
i=i+2;
[testArray insertObject:[testArray1 objectAtIndex:k] atIndex:i];
}
NSMutableArray *array1,*array2;
//////array1 and array2 initialise it with your values
NSMutableArray *finalArray = [[NSMutableArray alloc]init]
int totalcount = 0;
if (array1.count > array2.count) {
totalcount = array1.count;
}
else
totalcount = array2.count;
for (int i = 0; i<totalcount; i++) {
if (i <= array1.count-1) {
[finalArray addObject:[array1 objectAtIndex:i]];
}
if (i <= array2.count-1) {
[finalArray addObject:[array2 objectAtIndex:i]];
}
}

Auto-incrementing a key in a NSMutableDictionary

I want to auto-incrementing a key and at to a NSMutableDictionary.
I tried to do it but it wasn't work :
NSMutableDictionary *array = [[NSMutableDictionary alloc] init];
int testAutoIndex = 0;
[array setObject:[NSNumber numberWithInt:testAutoIndex++] forKey:#"index"];
[array release];
Thanks :)
Use this:
NSMutableDictionary *array = [[NSMutableDictionary alloc] init];
int testAutoIndex = 0;
[array setObject:[NSNumber numberWithInt:++testAutoIndex] forKey:#"index"];
[array release];
If you want to create a dictionary with say N entries, then it is possible to do using the code
int N = 100; // or what ever number you want
NSArray *arrayOfObjectsYouWantToPumpIntoDictionary = ....;
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:100];
for(int i=0;i<N;i++){
NSString *key = [NSString stringWithFormat:#"%d"i];
[mutableDictionary setObject:[arrayOfObjectsYouWantToPumpIntoDictionary objectAtIndex:i] forKey:];
}
// Later some where else if you want to retrieve object with key of x (x can be 1, or 2 or what ever value), you can do
objectToBeRetrieved = [mutableDictionary objectForKey:[NSString stringWithFormat:#"%d",x];

Sum duplicate on NSMutableArray

I have a NSMutableArray with objects of type NSMutableDictionary,
the NSMutableDictionary contains 2 keys
-Airlines (string)
-Rating (integer)
I have an NSMutableArray with all the objects and what i need is to Sum the rating of all the airline companies repeated objects, an example:
Airline Rating
A 2
B 3
B 4
C 5
The end result array will be the A = 2, C = 5 and the Sum of B´s that is equal to 7.
My code so far:
for (int i = 0; i < arrayMealRating.count; ++i) {
NSMutableDictionary *item = [arrayMealRating objectAtIndex:i];
NSLog(#"item=%#",item);
for (int j = i+1; j < arrayMealRating.count; ++j)
{
if ([[item valueForKey:#"Airline"] isEqualToString:[arrayMealRating objectAtIndex:j]]){
NSMutableDictionary *item = [arrayMealRating objectAtIndex:j];
NSMutableDictionary *item1 = [arrayMealRating objectAtIndex:i];
NSInteger auxCount = [[item valueForKey:#"setMealRating"] integerValue] + [[item1 valueForKey:#"setMealRating"] integerValue];
NSMutableDictionary *aux = [NSMutableDictionary dictionaryWithObjectsAndKeys:[item valueForKey:#"Airline"], #"Airline"
,[NSString stringWithFormat:#"%d",auxCount], #"setMealRating"
,nil];
NSLog(#"aux=%#",aux);
[arrayMealRating replaceObjectAtIndex:i withObject:aux];
}
}
}
A bit messy i know but i dont know how to work with NSMutableDictionary, any help will be much appreciated, Thanks in Advance!
Incase you dont want to change how your storing the data, heres how you would do it using key-value coding. Heres the dirrect link to the documentation for #distinctUnionOfObjects and #sum.
// Get all the airline names with no duplicates using the KVC #distinctUnionOfObjects collection operator
NSArray *airlineNames = [arrayMealRating valueForKeyPath:#"#distinctUnionOfObjects.Airline"];
// Loop through all the airlines
for (NSString *airline in airlineNames) {
// Get an array of all the dictionaries for the current airline
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(Airline == %#)", airline];
NSArray *airlineMealRating = [arrayMealRating filteredArrayUsingPredicate:predicate];
// Get the sum of all the ratings using KVC #sum collection operator
NSNumber *rating = [airlineMealRating valueForKeyPath:#"#sum.Rating"];
NSLog(#"%#: %#", airline, rating);
}
This gives the following output
A: 2
B: 7
C: 5
I would suggest to redesign that entirely if that's at all possible.
Create a class Airline
#interface Airline : NSObject
#property (strong, nonatomic) NSString *name;
#property (strong, nonatomic) NSMutableArray *mealRatings;
- (void)addMealRating:(float)rating;
- (float)sumOfMealRatings;
#end
#implementation
- (id)initWithName:(NSString *)pName
{
self = [super init];
if (self)
{
self.name = pName;
self.mealRatings = [NSMutableArray array];
}
return self;
}
- (void)addMealRating:(float)rating
{
[self.mealRatings addObject:#(rating)];
}
- (float)sumOfRatings
{
float sum = 0;
for (NSNumber *rating in self.mealRatings)
{
sum += [rating floatValue];
}
}
#end
Then in your 'mainclass' you simply hold an NSArray with instances of your Airline objects. It might require you to change some of your existing code, but I think in the long run it saves you time and trouble. Perhaps you recognize later on, that you want to add additional properties to your Airlines. A dictionary is a cumbersome way to do that.
#try this
NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:4];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[NSNumber numberWithInteger:2] forKey:#"A"];
[myArray addObject:dict];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
[dict2 setValue:[NSNumber numberWithInteger:3] forKey:#"B"];
[myArray addObject:dict2];
NSMutableDictionary *dict3 = [[NSMutableDictionary alloc] init];
[dict3 setValue:[NSNumber numberWithInteger:4] forKey:#"B"];
[myArray addObject:dict3];
NSMutableDictionary *dict4 = [[NSMutableDictionary alloc] init];
[dict4 setValue:[NSNumber numberWithInteger:5] forKey:#"D"];
[myArray addObject:dict4];
NSMutableDictionary *resultDictionary = [[NSMutableDictionary alloc] init];
for(NSMutableDictionary *dictionary in myArray)
{
NSString *key = [[dictionary allKeys] objectAtIndex:0];
NSInteger previousValue = [[resultDictionary objectForKey:key] integerValue];
NSInteger value = [[dictionary objectForKey:key] integerValue];
previousValue += value;
[resultDictionary setObject:[NSNumber numberWithInteger:previousValue] forKey:key];
}
for(NSString *key in resultDictionary)
{
NSLog(#"value for key = %# = %d",key, [[resultDictionary valueForKey:key] integerValue]);
}

copying three different array to one array

I have three array..say array1,array2,array3. All these arrays contains dictionary.Now, I want to copy all the objects of these array into a single array and display in table view.
My problem is that how will I copy those three array into 1.
Say;
NSMutableArray *array1 = [NSMutableArray arrayWithObject:Dict1];
NSMutableArray *array2 = [NSMutableArray arrayWithObject:Dict2];
NSMutableArray *array3 = [NSMutableArray arrayWithObject:Dict3];
Now, I want to copy the contains of array1, array2, array3 into array4.How will I do this.
Use this
NSMutableArray *array4 = [[NSMutableArray alloc] init];
[array4 addObjectsFromArray:array1];
[array4 addObjectsFromArray:array2];
[array4 addObjectsFromArray:array3];
//Do something on array4
[array4 release];
NSMutableArray *allObjs = [[NSMutableArray alloc] initWithArray: array1];
[allObjs addObjectsFromArray: array2];
[allObjs addObjectsFromArray: array3];
NSMutableArray *array4 = [[NSMutableArray alloc] init];
for (int i = 0; i < [array1 count]; i++)
{
[array4 addObject:[array1 objectAtIndex:i]];
}
for (int i = 0; i < [array2 count]; i++)
{
[array4 addObject:[array2 objectAtIndex:i]];
}
for (int i = 0; i < [array3 count]; i++)
{
[array4 addObject:[array3 objectAtIndex:i]];
}
//use your array4
[array4 release];
NSMutableArray * array4 = [NSMutableArray arrayWithObjects:[array1 objectAtIndex:0], [array2 objectAtIndex:0], [array3 objectAtIndex:0]];

Memory leak in NSMutableArray, NSArray, NSString in iPhone SDK

In my app, I got Memory leaks in NSMutableArray, NSArray and NSString.
Here is the code.
NSString *subQuery = [NSString stringWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
NSArray *subArray1 = [[[self returnExecuteQuery:subQuery] mutableCopy] autorelease];
[subArray addObjectsFromArray:subArray1];
NSString *columnQuery = [NSString stringWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
NSArray *newArray =[[[self returnExecuteQuery:columnQuery] mutableCopy] autorelease];
[langArray addObjectsFromArray:newArray];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:[NSString stringWithFormat:#"%#",lblshortName.text]];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[tempArray addObject:[NSString stringWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
}
else {
[tempArray addObject:#"<empty>"];
}
NSString *detail = #"_________________";
for (int j=0; j<[lableNameArray count]; j++) {
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:[NSString stringWithFormat:#"%#",[lableNameArray objectAtIndex:j]]];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
detail = [NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4];
}
}
[detailTextArray addObject:detail];
}
When I run in Instruments I got leaks in
-subArray1 in second line.
-detail (NSString) in second for loop.
And subArray and langArray are my global arrays.
If I remove mutableCopy from NSArray *newArray =[[[self returnExecuteQuery:columnQuery] mutableCopy] autorelease]; and NSArray *subArray1 = [[[self returnExecuteQuery:subQuery] mutableCopy] autorelease]; then subArray and langArray doesnot retain values.
How to avoid memory leak in this code?
Olease try this one, in above code you are creating two many objects that belong to autorelease pool here is one version where I tried to handle release of those string variables.
Second this is that the leak of detail is because you are de-referencing it many times in your code. And for subArray1 please see the comment
NSMutableString *subQuery =[ [NSMutableString alloc] initWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
// please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *subArray1 = [[self returnExecuteQuery:subQuery] mutableCopy] ;
[subArray addObjectsFromArray:subArray1];
[subQuery release];
NSMutableString *columnQuery ==[ [NSMutableString alloc] initWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
NSArray *newArray =[[self returnExecuteQuery:columnQuery] mutableCopy] ;
[langArray addObjectsFromArray:newArray];
[columnQuery relese];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSMutableString *tempKey = [[NSMutableString alloc]initWithFormat:#"%#",lblshortName.text]];
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:tempKey];
[tempKey release];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSMutableString *tempString = [[NSMutableString alloc] initWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
[tempArray addObject:tempString];
[tempString release];
}
else {
[tempArray addObject:#"<empty>"];
}
NSMutableString *detail = nil;
for (int j=0; j<[lableNameArray count]; j++)
{
detail = [[ NSMutableString alloc]initWithString:#"_________________"];
NSMutableString *key = [[NSMutableString alloc]initWithFormat:#"%#",[lableNameArray objectAtIndex:j]];
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:key];
[key release];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail setString:[NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
}
[detailTextArray addObject:detail];
[detail release];
}
}
[subArray1 release];
[newArray release];
UPDATE : Please do read comments in the code and reply back so that things could be improved.
NSMutableString *subQuery =[ [NSMutableString alloc] initWithFormat:#"SELECT %# FROM tbl_lang WHERE glossary = '%#'",append1,glossaryName];
//*****NOTE THIS POINT ----> please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *subArray1 = [[self returnExecuteQuery:subQuery] mutableCopy] ;
[subArray addObjectsFromArray:subArray1];
[subQuery release];
NSMutableString *columnQuery ==[ [NSMutableString alloc] initWithFormat:#"select AutoID,%# from tbl_lang where glossary='%#'",lblshortName.text,glossaryName];
//*****NOTE THIS POINT ----> please make returnExecuteQuery's returned array autorelease if it is not.
NSArray *newArray =[[self returnExecuteQuery:columnQuery] mutableCopy] ;
[langArray addObjectsFromArray:newArray];
[columnQuery relese];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<[newArray count]; i++) {
NSMutableString *tempKey = [[NSMutableString alloc]initWithFormat:#"%#",lblshortName.text]];
NSString *cellText = [[newArray objectAtIndex:i] valueForKey:tempKey];
[tempKey release];
if (cellText != (NSString *)[NSNull null] && ![cellText isEqualToString:#""] ) {
NSString *decodedString3 = [NSString stringWithUTF8String:[cellText cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSMutableString *tempString = [[NSMutableString alloc] initWithFormat:#"%# : %#",lblshortName.text, decodedString3]];
[tempArray addObject:tempString];
[tempString release];
}
else {
[tempArray addObject:#"<empty>"];
}
NSMutableString *detail = [[ NSMutableString alloc]initWithString:#"_________________"];
for (int j=0; j<[lableNameArray count]; j++)
{
NSMutableString *key = [[NSMutableString alloc]initWithFormat:#"%#",[lableNameArray objectAtIndex:j]];
NSString *checkNull=[[subArray1 objectAtIndex:i] valueForKey:key]; //also here if you note you are using subArray1 not subArray?
[key release];
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail setString:[NSString stringWithFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
break;//I am not sure why you are checking this condition but assume that you want to get NOT NULL VALUE and add it to array?
}
}
[detailTextArray addObject:detail];
[detail release];
}
[subArray1 release];
[newArray release];
UPDATE 2:
if(checkNull != (NSString *)[NSNull null] && checkNull.length > 0)
{
NSString *decodedString4 = [NSString stringWithUTF8String:[checkNull cStringUsingEncoding:[NSString defaultCStringEncoding]]];
[detail appendFormat:#"%#\n%# : %# ",detail,[lableNameArray objectAtIndex:j],decodedString4]];
}
Thanks,
Not sure what is causing the memory leak, but this may help. This is a more direct way of copying the arrays, and may result in avoiding the leak:
NSArray *langArray =[[NSArray alloc] initWithArray: [self returnExecuteQuery:columnQuery] copyItems: YES];
This basically makes a one-level deep copy of the array returned by returnExecuteQuery. You can read about it in more detail in Collections Programming Topics.
I'm not sure how mutableCopy works and that may have something to do with the leak. If it copies the objects in the old array & then adds them to the new array, they may enter the array with a retain count of 2 (1 from the copy, and 1 from being added to an array.) It doesn't make much sense that it should work this way. But, if it does, that could account for the leak.
You could start by releasing your tempArray once done with it (after the loops).
Often, the higher levels leaks are hidden in the flood of lower level ones (ie a container leaking causes all its content to be leaked as well), which might be the case for your string.
Using mutableCopy] autorelease]; is fine by the way.