I want to replace Json values to another string values in iOS - ios

Using Json I have retrieve some values to UITableViewCell
NSString *sample = [[array objectAtIndex:indexPath.row] objectForKey:#"food"];
I am getting 1,2,3,4,6 in my sample string values
But I want to show like, if for example 1=apple 2=grape 3=orange 4=pineapple 5=lemon 6=All
I want the result to be apple,grape,orange,pineapple,All in my sample string values

In Objective-C there is no built in enums available for String types. You can declare enums as Integer and then make a function or an array of strings which return the string value for that enum.
Declare in your .h file.
typedef NS_ENUM(NSInteger, FRUIT) {
APPLE = 1,
GRAPE,
ORANGE,
PINEAPPLE,
LEMON,
All
};
extern NSString * const FRUITString[];
Define in your .m file.
NSString * const FRUITString[] = {
[APPLE] = #"APPLE",
[GRAPE] = #"GRAPE",
[ORANGE] = #"ORANGE",
[PINEAPPLE] = #"PINEAPPLE",
[LEMON] = #"LEMON",
[All] = #"All"
};
and you can use it like:
NSLog(#"%#", FRUITString[APPLE]);
// OR
NSLog(#"%#", FRUITString[1]);
Output: APPLE
Based on your comment: if food values is "food":"1,2" I want to show "apple,grape"
NSString *foodValue = #"1,2";
NSArray *values = [foodValue componentsSeparatedByString:#","];
NSMutableArray *stringValues = [[NSMutableArray alloc] init];
for (NSString *value in values) {
[stringValues addObject:FRUITString[[value integerValue]]];
}
NSLog(#"%#", [stringValues componentsJoinedByString:#","]);
APPLE,GRAPE

Change your code objectForKey#"" to valueForKey#""
NSString *sample = [[array objectAtIndex:indexPath.row] valueForKey:#"food"];

Define a NSDictionary with your required mapping, and fetch the value from your mapping dictionary:
NSDictionary *foodDict = #{
#"1": #"apple",
#"2": #"grape",
#"3": #"orange",
#"4": #"pineapple",
#"5": #"lemon",
#"6": #"all"
};
NSString *sample = [[array objectAtIndex:indexPath.row] objectForKey:#"food"];
NSString *sampleValue= [foodDict valueForKey:sample];
"sampleValue" is your required String Value needed. (Cast it to NSString if required)

Related

How to query an NSDictionary using an expression written in NSString?

I want to be able to run the following hypothetical function called evaluateExpression:on: and get "John" as answer.
NSDictionary *dict = #{"result": #[#{#"name": #"John"}, #{#"name": #"Mary"}]};
NSString *expression = #"response['result'][0]['name']";
NSString *answer = [self evaluateExpression: expression on: dict];
Is this possible?
There's an NSObject category that extends valueForKeyPath to give valueForKeyPathWithIndexes. It lets you write this:
NSDictionary *dict = #{#"result": #[#{#"name": #"John"}, #{#"name": #"Mary"}]};
NSString *path = #"result[0].name";
NSString *answer = [dict valueForKeyPathWithIndexes:path];
XCTAssertEqualStrings(answer, #"John");
The category is by psy, here: Getting array elements with valueForKeyPath
#interface NSObject (ValueForKeyPathWithIndexes)
-(id)valueForKeyPathWithIndexes:(NSString*)fullPath;
#end
#import "NSObject+ValueForKeyPathWithIndexes.h"
#implementation NSObject (ValueForKeyPathWithIndexes)
-(id)valueForKeyPathWithIndexes:(NSString*)fullPath
{
NSRange testrange = [fullPath rangeOfString:#"["];
if (testrange.location == NSNotFound)
return [self valueForKeyPath:fullPath];
NSArray* parts = [fullPath componentsSeparatedByString:#"."];
id currentObj = self;
for (NSString* part in parts)
{
NSRange range1 = [part rangeOfString:#"["];
if (range1.location == NSNotFound)
{
currentObj = [currentObj valueForKey:part];
}
else
{
NSString* arrayKey = [part substringToIndex:range1.location];
int index = [[[part substringToIndex:part.length-1] substringFromIndex:range1.location+1] intValue];
currentObj = [[currentObj valueForKey:arrayKey] objectAtIndex:index];
}
}
return currentObj;
}
#end
Plain old valueForKeyPath will get you close, but not exactly what you asked for. It may be useful in this form though:
NSDictionary *dict = #{#"result": #[#{#"name": #"John"}, #{#"name": #"Mary"}]};
NSString *path = #"result.name";
NSString *answer = [dict valueForKeyPath:path];
XCTAssertEqualObjects(answer, (#[#"John", #"Mary"]));
After spending quite a while trying to tackle this problem in the most efficient way, here's another take I came up with: Use javascript.
The above approach posted by Ewan definitely takes care of the problem, but I had some additional custom features I wanted to add, and objective-c approach became too complex very quickly. I ended up writing eval code in javascript and integrating it into objective-c using JavascriptCore. With that, it becomes as simple as one line of eval() call.

select indexOfObject from NSArray in Xcode by comparing string

Hi I have NSarray values in Xcode. I need to get array indexOfObject by comparing string values.
my array values are
(
{
firstName = lord;
lastname = krishna;
},
{
firstName = priya;
lastname = amirtha;
}
)
If I type first name in textfield and click button means last name want to display in another textfield.
thank you.
To answer the title of your question:
NSString *compareString = #"something";
NSMutableArray *indexesOfMatches = [[NSMutableArray alloc]init];
for (NSString *string in theArray) {
if ([string isEqualToString:compareString]) {
NSNumber *index = [[NSNumber numberWithInterger:[theArray indexOfObject:string]];
[indexOfMatches addObject:index];
}
}
//indexOfMatches will now contain NSNumber objects that represent the indexes of each of the matching string objects in the array
I think that using an NSDictionary would be better for you though. Then you can simply keep the first and last names as Key Value pairs.
NSDictionary *names = #{#"lord" : #"krishna", #"priya" : #"amirtha" };
Then you can just do value for key when you get the first name:
NSString *firstName = #"lord";
NSString *lastName = [names valueForKey:firstName];
Store firstNameArray and lastNameArray a mutable array NSMutableArray.
Using Fast Enumeration. Suppose array is the array you are provided with
for (NSDictionary *item in array) {
[firstNameArray addObject:[item objectForKey:#"firstName"]];
[lastNameArray addObject:[item objectForKey:#"lastName"]];
}
After entering the data in firstNameTextField click the button
Button action method implementation
-(IBAction)btnClicked:(id)sender {
NSInteger index = [firstName indexOfObject:[firstNameTextField text]];
[lastNameTextField setText:[lastName objectAtIndex:index]];
}

add convert UTF8 string to array

i converting Hebrew string and trying yo add it to array , this is the code:
NSMutableArray * myarray;
// #property(strong,nonatomic) NSMutableArray *stringArray;
for (NSString * item in stringArray) {
NSData * UTF8 = [item dataUsingEncoding:NSUTF8StringEncoding];
NSString * myString = [[NSString alloc] initWithData:UTF8 encoding:NSUTF8StringEncoding];
NSLog(#"myString = %#",myString); // Hebrew str log fine
[myarray addObject:myString];
}
NSString * ConvetData = [NSString stringWithFormat:#"%#",myarray];
NSLog(#"ConvetData = %#",ConvetData); // null
newitem.ingredient = ConvetData;
the array coms out as null , how can i crate one string from my convert data?
You need to initialize myarray: NSMutableArray *myarray =[[NSMutableArray alloc] init];

NSString remove duplicated substrings

How can I remove duplicated substings from string? For ex. I have: aaa,bbb,ttt,bbb,rrr.
And in result I want to have aaa,bbb,ttt,rrr (deleted duplicated bbb). I hope for your help. Thanks.
You can do it like this:
NSMutableSet *seen = [NSMutableSet set];
NSMutableString *buf = [NSMutableString string];
for (NSString *s in [str componentsSeparatedByString:#","]) {
if (![seen containsObject:s]) {
[seen add:s];
[buf appendFormat:#",%#", s];
}
}
NSString *res = [buf length] ? [buf substringFromIndex:1] : #"";
Do it in three steps
1) NSArray *items = [theString componentsSeparatedByString:#","];
2) remove duplicate element from array
NSArray* array = [NSArray arrayWithObjects:#"test1", #"test2", #"test1", #"test2",#"test4", nil];
NSArray* filteredArray = [[NSArray alloc] init];
NSSet *set= [NSOrderedSet orderedSetWithArray:array];
filteredArray = [set allObjects];
3) Concate String from array
NSString *myString = [myArray componentsJoinedByString:#","];
You can use NSMutableDictionary;
In dictionary there are two elements;
1. Key
2. Value
Just set Keys as your array elements;
Special point is that 'Key' can't be duplicate;
Now just get array of Keys by using [dictionary allKeys];
Now, at this stage you have unique values in new array;

All elements of nsarray are present in nsstring or not

I want to scan NSString (case insensitive) to check whether all elements of an array contain in that String or not ?
Eg.
NSString *string1 = #"Java is pass by value : lets see how?";
NSString *string2 = #"Java is OOP Language";
NSArray *array = [[NSArray alloc] initWithObjects:#"Java",#"Pass",#"value", nil];
In this case string1 pass the test as it contain all keyword from array (i.e. Java,Pass,Value).
So, how can i achieve this functionality ?
I don't test it for speed, and it will fail on case-sensitive strings, but here's another solution (just in case)
NSArray *components = [string1 componentsSeparatedByString:#" "];
NSSet *textSet = [NSSet setWithArray:components];
NSSet *keywordsSet = [NSSet setWithArray:array];
BOOL result = [keywordsSet isSubsetOfSet:textSet];
Keep in mind that componentsSeparatedByString will tokenize very silly, like "how?" instead of "how" you need.
BOOL containsAll = YES;
for (NSString *test in array) {
if ([string1 rangeOfString:test].location == NSNotFound) {
containsAll = NO;
break;
}
}

Resources