Reputation:
Working in Objective-C where I need to parse JSON. So after parsing successfully.
Below is my code :
-(instancetype)initWithDict:(NSDictionary *)dict {
self = [super init];
if (self) {
if ([dict isKindOfClass:[NSDictionary class]]) {
self.allKeysArray = [dict allKeys];
if ([self.allKeysArray containsObject:@"nDetail"]) {
if ([dict valueForKey:@"nDetail"]) {
_tempNutrientArray = [[[dict valueForKey:@"nDetail"] valueForKey:@"nTypeCode"] valueForKey:@"value"];
}
}
}
NSLog(@"N Array : @%@", _tempNutrientArray);
}
I need to convert this in string format each an every value.
My output :
N Array : @(
"ENER-",
FAT,
FASAT,
CHOAVL,
"SUGAR-",
"PRO-",
NACL
)
Required Output :
N Array : @("ENER-","FAT","FASAT","CHOAVL","SUGAR-","PRO-","NACL")
So how should I convert it to string format. Please help me.
Upvotes: 0
Views: 104
Reputation: 350
As the required output you need, you can try:
-(instancetype)initWithDict:(NSDictionary *)dict {
self = [super init];
if (self) {
if ([dict isKindOfClass:[NSDictionary class]]) {
self.allKeysArray = [dict allKeys];
if ([self.allKeysArray containsObject:@"nDetail"]) {
if ([dict valueForKey:@"nDetail"]) {
_tempNutrientArray = [[[dict valueForKey:@"nDetail"] valueForKey:@"nTypeCode"] valueForKey:@"value"];
}
}
}
NSString *finalString = @"";
[_tempNutrientArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSString *plainstr = [NSString stringWithFormat:@"%@",obj];
if (plainstr)
finalString = [finalString stringByAppendingString:plainstr];
}];
NSLog(@"N Array : @%@", finalString);
}
Upvotes: 0
Reputation: 4815
In your case you have create one variable that store your whole string from your response after that use my code.
NSString *tempstring = @"ENER- FAT FASAT CHOAVL SUGAR- PRO- NACL";
NSArray *arr = [tempstring componentsSeparatedByString:@" "];
NSLog(@"%@",arr);
NSLog(@"First value : %@",[arr objectAtIndex:0]);
NSLog(@"Second value : %@",[arr objectAtIndex:1]);
NSLog(@"Third value : %@",[arr objectAtIndex:2]);
now check arr value you got all string in array that you want .
Output :
(
"ENER-",
FAT,
FASAT,
CHOAVL,
"SUGAR-",
"PRO-",
NACL
)
First value : ENER-
Second value : FAT
Third value : FASAT
Upvotes: 0
Reputation: 1303
You need to enumerate the whole array to make all object as a proper string. This may be fast operation.
you can use this code:
NSArray *arr = [NSArray arrayWithObjects:@"",@"", nil];
NSMutableArray *arrNew = [NSMutableArray new];
[arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSString *plainstr = [NSString stringWithFormat:@"%@",obj];
[arrNew addObject:plainstr];
}];
The arrNew will be the array with string..
Better you convert it to string when you are fetching it.
Upvotes: 1
Reputation: 1304
Converting Array to String
NSString * myString = [_tempNutrientArray componentsJoinedByString:@""];
If you want any Character between the string give it in componentsJoinedByString:@"GIVE_IT_HERE"
Upvotes: 0