Dictionary object can't convert into a JSON object objective-c - ios

hello I have a NSMutableArray like this.
<__NSArrayM 0x137e9f270>(
{
CanLoadMore = 0;
IsFinalLevel = 1;
NextLevelApprovers = (
);
OrgStructure = (
{
CreatedBy = 1;
CreatedDate = "2015-07-29T12:10:34.297";
Deleted = 0;
DeletedBy = 0;
DeletedDate = "1901-01-01T00:00:00";
EntityHeadCode = 17098;
EntityHeadName = "<null>";
IsPermitted = 0;
LegislativeCode = LKA;
LevelId = 1;
NodeId = 1;
OrgEntity = Group;
OrgLevelDescription = "";
OrgLevelName = "ABCD Holdings";
OrgStructureId = 1;
ParentNodeId = 0;
RefOrgLevelId = 1;
Status = 1;
UpdatedBy = 17113;
UpdatedDate = "2016-04-07T08:53:13.727";
},
{
CreatedBy = 17113;
CreatedDate = "2016-04-06T12:17:19.75";
Deleted = 0;
DeletedBy = 0;
DeletedDate = "1901-01-01T00:00:00";
EntityHeadCode = 0;
EntityHeadName = "<null>";
IsPermitted = 0;
LegislativeCode = LKA;
LevelId = 2;
NodeId = 2;
OrgEntity = Company;
OrgLevelDescription = "";
OrgLevelName = "ABCD HCM";
OrgStructureId = 2;
ParentNodeId = 1;
RefOrgLevelId = 6;
Status = 1;
UpdatedBy = 17098;
UpdatedDate = "2016-07-29T11:14:12.513";
}
);
PreviousLevelCount = 0;
RequestDetails = {
AutoId = 20;
LevelId = 1;
ModuleId = 2;
NoOfLevels = 1;
ObjectId = 20;
ObjectName = "Leave Request";
RequestForm = "{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}";
RequestId = 20;
RequestedDate = "2016-08-02T05:07:07.127";
WorkflowId = 2;
};
RequesterDetails = {
AdminRequesterName = "";
DisplayName = "<null>";
EmployeeCode = 17227;
EmployeeNumber = MM0000019;
EtfNo = "";
Gender = Female;
ImagePath = "/profile/image/759006c5e4214f0";
Name = haniAAAA;
};
}
)
I want to convert this to JSON object. So I did like this.
NSError *jsonError;
NSData *objectData = [[[[dm.mutArraySelectedReq objectAtIndex:index] objectForKey:#"RequestDetails"] valueForKey:#"RequestForm"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
but my jsondictionary is always nil. What is the error with this RequestForm object.
Please help me.
Thanks
UPDATE
This is the string I want to convert into a json.
{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}
UPDATE - CORRECT STRING
{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17167,\"LeaveYear\":2016,\"LeaveTypeCode\":2,\"LeaveReasonCode\":0,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-01T00:00:00\",\"EndDate\":\"2016-08-01T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"full\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/01/2016\",\"EndDateString\":\"08/01/2016\",\"LeaveDayList\":[\"08/01/2016-FH,08/01/2016-SH\"],\"SystemLeaveTypeCode\":\"CAS\",\"LeaveTypeName\":\"CASUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":null,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}
WRONG STRING
{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}

Its working Fine
NSString *str = #"{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17167,\"LeaveYear\":2016,\"LeaveTypeCode\":2,\"LeaveReasonCode\":0,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-01T00:00:00\",\"EndDate\":\"2016-08-01T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"full\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/01/2016\",\"EndDateString\":\"08/01/2016\",\"LeaveDayList\":[\"08/01/2016-FH,08/01/2016-SH\"],\"SystemLeaveTypeCode\":\"CAS\",\"LeaveTypeName\":\"CASUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":null,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}" ;
NSError *jsonError;
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&jsonError];
**OutPut**
Printing description of json:
{
AttachedDocument = "<null>";
BaseLeaveType = ANN;
BaseType = ess;
CoveringPersonCode = 0;
CoveringPersonName = "<null>";
CreatedBy = 0;
CreatedDate = "0001-01-01T00:00:00";
Deleted = 0;
DeletedBy = 0;
DeletedDate = "0001-01-01T00:00:00";
DocumentSource = LEAVE;
Employee = "<null>";
EmployeeCode = 17167;
EndDate = "2016-08-01T00:00:00";
EndDateSession = full;
EndDateString = "08/01/2016";
ForDate = "1901-01-01T00:00:00";
LeaveDayList = (
"08/01/2016-FH,08/01/2016-SH"
);
LeaveEntryCode = 0;
LeaveReasonCode = 0;
LeaveReasonName = "Leave TypeCasual - Leave - Leave Reason";
LeaveTypeCode = 2;
LeaveTypeName = CASUAL;
LeaveYear = 2016;
LieuDayList = "<null>";
ModuleId = 2;
NoOfDays = 1;
ObjectId = 20;
PreApproved = 0;
Remarks = "";
RequestId = 0;
RequestStatus = P;
StartDate = "2016-08-01T00:00:00";
StartDateSession = full;
StartDateString = "08/01/2016";
Status = 0;
SystemLeaveTypeCode = CAS;
UpdatedBy = 0;
UpdatedDate = "0001-01-01T00:00:00";
}

Try
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:0
error:&jsonError];
Don't give any options.

Related

Remove " " from key string in a NSMutableDictionary

Here's my dictionary:
Birthdate = "01-01-0001";
CareerField = 3;
Gender = 2;
"Interests[0].UserProfileId" = 19594;
"Interests[0].UserSurveyId" = 1;
SocialStatus = 2;
Studies = 3;
But I want the Interests key to be without "".Like that:
Birthdate = "01-01-0001";
CareerField = 3;
Gender = 2;
Interests[0].UserProfileId = 19594;
Interests[0].UserSurveyId = 1;
SocialStatus = 2;
Studies = 3;
UPDATE:
Interests i must send them like array.
[dict setObject:self.birthdayDate forKey:#"Birthdate"]
[dict setObject:#(self.occupationPickerRow + 1) forKey:#"CareerField"];
for (int i = 0; i < [interestsArray count]; i++) {
NSString *stringSurveyId = [NSString stringWithFormat:#"%#%d%#", #"Interests[", indexCount, #"].UserSurveyId"];
NSString *stringUserProfileId = [NSString stringWithFormat:#"%#%d%#", #"Interests[", indexCount, #"].UserProfileId"];
[dict setObject:[interestsArray objectAtIndex:i] forKey:stringSurveyId];
[dict setObject:#([[[MZEngine sharedInstance] currentUserModel] userId]) forKey:stringUserProfileId];
indexCount++;
}

Retrieve a data from json ios

This is the content of dictionary *data
Data = {
Specialities = (
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = "<null>";
Photos = "<null>";
ServiceDescription = 356563;
Speciality = 22;
SpecialityName = "Wedding Photographer";
UserFRPs = "<null>";
Videos = (
{
VideoId = TWhSjpsGvPQ;
VideoLink = "http://www.youtube.com/watch?v=TWhSjpsGvPQ";
VideoType = YouTube;
},
{
VideoId = N2CJrhHEydA;
VideoLink = "http://www.youtube.com/watch?v=N2CJrhHEydA";
VideoType = YouTube;
},
{
VideoId = Lq6faQVYcwY;
VideoLink = "http://www.youtube.com/watch?v=Lq6faQVYcwY";
VideoType = YouTube;
},
{
VideoId = v8WjMiodcKo;
VideoLink = "http://www.youtube.com/watch?v=v8WjMiodcKo";
VideoType = YouTube;
}
);
},
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = "<null>";
Photos = "<null>";
ServiceDescription = 52454353;
Speciality = 37;
SpecialityName = "Hair and Makeup Stylist";
UserFRPs = "<null>";
Videos = "<null>";
},
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = "<null>";
Photos = "<null>";
ServiceDescription = 21212;
Speciality = 55;
SpecialityName = Transport;
UserFRPs = "<null>";
Videos = "<null>";
}
);
};
}
This is the response i am getting from json, what logic should i write to retrieve "VideoId" linked to a specific "Speciality" (for ex- Speciality = 22)
if i write following code, i am getting all #"VideoId"
[[[[responseDictionary valueForKey:#"Data"]valueForKey:#"Specialities"]valueForKey:#"Videos"]valueForKey:#"VideoId"]
The parsing way will be something like:
NSDictionary *dataDict = [responseDictionary valueForKey:#"Data"];
NSMutableArray *specialityArray = [dataDict valueForKey:#"Specialities"];
NSDictionary *objectDict = [specialityArray objectAtIndex:your index (0/1/2)];
int *speciality = [[objectDict ValueForKey:#"Speciality"] intValue];
if(speciality = 22)
{
NSMutableArray *videoArray = [objectDict valueForKey:#"Videos"];
NSDictionary *videoObject = [videoArray objectAtIndex:your index (0/1/2)];
NSString *videoID = [videoObject valueForKey:#"VideoId"];
}
Parse the rest accordingly as per your need.
Use this code,
NSArray *wholeArray = [[responseDictionary objectForKey:#"Data"] valueForKey:#"Specialities"];
NSArray *subArray = [[wholeArray objectAtIndex:0] valueForKey:#"Videos"];
subArray is get all the videos values, then you get single value use this code,
NSString *videoID = [[subArray objectAtIndex:i] valueForKey:#"VideoId"];
or you will get all videoID in single variable use this below code,
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i = 0; i < subArray.count; i++) {
[tempArray addObject:[[subArray objectAtIndex:i] valueForKey:#"VideoId"]];
}
finally tempArray get All the VideoID values, anywhere you use,
NSString *videoID = [tempArray objectAtIndex:0/1/2];
hope its helpful

Issues parsing a dictionary

Below is a dictionary I have created by retrieving the my twitter statuses for an App Only twitter feed. I have parsed and returned the value of "text" successfully, and displayed it in a table view cell as follows:
static NSString *cellID = #"FeedCell3" ;
FeedCell3 *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[FeedCell3 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
NSInteger idx = indexPath.row;
NSDictionary *t = self.twitterDataSource[idx];
cell.updateLabel.text = t[#"text"];
return cell;
However, when I try to return other values for keys such as "profile_image_url" and "screen_name" using the method below, an (null) is returned, even though there is a value in the dictionary. What am I doing wrong?
cell.nameLabel.text = t[#"screen_name"];
NSURL *profileImageURL = t[#"profile_image_url"];
NSLog(#"%#", profileImageURL);
Dictionary Data:
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Thu May 01 20:15:32 +0000 2014";
entities = {
hashtags = (
);
symbols = (
);
urls = (
);
"user_mentions" = (
);
};
"favorite_count" = 0;
favorited = 0;
geo = "<null>";
id = 461962182734217473;
"id_str" = 46398745473;
"in_reply_to_screen_name" = "<null>";
"in_reply_to_status_id" = "<null>";
"in_reply_to_status_id_str" = "<null>";
"in_reply_to_user_id" = "<null>";
"in_reply_to_user_id_str" = "<null>";
lang = fr;
place = "<null>";
"retweet_count" = 0;
retweeted = 0;
source = web;
text = "Test Tweet";
truncated = 0;
user = {
"contributors_enabled" = 0;
"created_at" = "Sun Mar 23 21:18:10 +0000 2014";
"default_profile" = 1;
"default_profile_image" = 1;
description = "";
entities = {
description = {
urls = (
);
};
};
"favourites_count" = 0;
"follow_request_sent" = "<null>";
"followers_count" = 1;
following = "<null>";
"friends_count" = 6;
"geo_enabled" = 0;
id = 24072342084;
"id_str" = 242344084;
"is_translation_enabled" = 0;
"is_translator" = 0;
lang = en;
"listed_count" = 0;
location = "";
name = "My Name";
notifications = "<null>";
"profile_background_color" = C0DEED;
"profile_background_image_url" = "http://abs.twimg.com/images/themes/theme1/bg.png";
"profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme1/bg.png";
"profile_background_tile" = 0;
"profile_image_url" = "http://abs.twimg.com/sticky/default_profile_images/default_profile_1_normal.png";
"profile_image_url_https" = "https://abs.twimg.com/sticky/default_profile_images/default_profile_1_normal.png";
"profile_link_color" = 0084B4;
"profile_sidebar_border_color" = C0DEED;
"profile_sidebar_fill_color" = DDEEF6;
"profile_text_color" = 333333;
"profile_use_background_image" = 1;
protected = 0;
"screen_name" = ScreenName;
"statuses_count" = 2;
"time_zone" = "<null>";
url = "<null>";
"utc_offset" = "<null>";
verified = 0;
};
Those latter two keys you're going for are in the user dictionary, so try
t[#"user"][#"screen_name"];
t[#"user"][#"profile_image_url"];
The second issue will appear when you solve the first. The url is a string. To get a proper NSURL you'll need to use an NSURL class method.
NSURL *aURL = [NSURL URLWithString:t[#"user"][#"profile_image_url"]];

Merge the same objects inside array IOS

I have an array which contains this objects:
(
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 112;
iShiftId = 1;
sItemName = "";
sModifier = "";
}
)
I need to merge the contents of array if the objects are same and modify the object inside that array in such a way that it should be like this:
(
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 3;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 112;
iShiftId = 1;
sItemName = "";
sModifier = "";
}
)
As you can see, the entry for object with iItemDayPriceId = 143 becomes 1 only with fQty = 3.
I have tried using the code here: How to Find Duplicate Values in Arrays?
But it is only comparing 2 objects at a time.
Edit: Oops, I missed your count requirement.
Edit 2: And the fact that you wanted to mutate the given array rather the build a new one.
Depends on what you mean by distinct but since it looks like you mean to compare the contents and not the references, you should build a new array so that if the comparison is true you increment the count and otherwise you add the object.
Mutate existing array
Disclaimer: probably not my best work here.
I would appreciate if someone could suggest how to improve this because I am pretty sure it is not the best way to do this and may not even work (don't have access to an Obj-C compiler at the moment).
Foo objectA = [Foo new];
objectA.Bar = #"Bar";
Foo objectB = [Foo new];
objectB.Bar = #"Bar";
Foo objectC = [Foo new];
objectC.Bar = #"Not Bar";
NSMutableArray *array = #[objectA, objectB, objectC];
NSMutableDictionary *countDictionary = [[NSMutableDictionary alloc] init];
for (Foo *foo in [array copy])
{
bool found = false;
for (Foo *key in countDictionary)
{
if ([key isEqualTo:foo])
{
NSNumber *currentCount = [countDictionary objectForKey:key];
int currentIntCount = [currentCount intValue];
currentIntCount++;
[countDictionary setObject:[NSNumber numberWithInt:currentIntCount] forKey:key];
[array removeObject:key];
found = true;
break;
}
if (!found)
[countDictionary setObject:[NSNumber numberWithInt:1] forKey:foo];
}
}
for (Foo *realFoo in array)
{
NSNumber *countNumber = [countDictionary objectForKey:realFoo];
int countInt = [countNumber intValue];
realFoo.Count = countInt;
}
Build new array
Foo objectA = [Foo new];
objectA.Bar = #"Bar";
Foo objectB = [Foo new];
objectB.Bar = #"Bar";
NSMutableArray *array = #[objectA, objectB];
NSMutableArray *distinct = [[NSMutableArray alloc] init];
for (Foo *f in array)
{
bool found = false;
for (Foo *d in distinct)
{
if ([d isEqualTo:f])
{
found = true;
d.Count++;
}
break;
}
if (!found)
[distinct addObject:f];
}
And of course you would have to define an equality comparer for Foos, in this case for instance
-(bool) isEqualTo:(Foo *)nFoo
{
bool isEqual = false;
if ([self.Bar isEqualToString:nFoo.Bar])
isEqual = true;
return isEqual;
}
Having not dealt with Objective C in a while I should say that there may be some best-practices as to implementing equality comparison instead of rolling your own completely like this example
Use below code:
NSMutableArray* myArray =
[[NSMutableArray alloc]initWithObjects:
#"red",#"blue",#"red",#"green",#"yellow", #"33", #"33",#"red", #"123", #"123",nil];
NSOrderedSet *mySet = [[NSOrderedSet alloc] initWithArray:myArray];
myArray = [[NSMutableArray alloc] initWithArray:[mySet array]];
NSLog(#"%#",myArray);

How to check an object is a string or an array in ios

I am getting a response array from two different web services. But for the same methods. The problem is there 2 different web services give me bit different responses. These are those arrays
(NSMutableArray *) $2 = 0x003e9210 <__NSArrayM 0x3e9210>(
{
addedOn = "03/09/2013";
album = "Surendra Perera";
artistGroup = Female;
artists = "Surendra Perera";
bpm = 0;
categories = "Love Songs";
duration = "250.00";
energy = "";
era = Millenium;
extroTime = "0.00";
extroType = "";
genders = "";
id = 50;
imageUrl = "http://sample.com/CloudMusic/Images/sngfile.png";
introTime = "0.00";
language = Sinhala;
lyrics = "";
mediaUrl = "http://sample.com/CloudMusic/Music/0476/50.mp3";
moods = Lonely;
movie = "";
musicLabel = Evoke;
musician = "";
sDuration = "00:04:10";
soundCodes = "";
tempos = "";
textures = "";
thumbUrl = "http://sample.com/CloudMusic/Images/sngfile.png";
title = "Mee Mai Gaha";
writer = "";
year = "";
}
)
Other one is
addedOn = "19/09/2013";
albumName = Massina;
artists = (
{
artistGroup = 0;
description = "<null>";
id = 290;
imageUrl = "<null>";
name = Daddy;
noOfSongs = 0;
thumbUrl = "<null>";
}
);
duration = "260.00";
id = 2575;
imageUrl = "http://sample.com/CloudMusic/Images/sngfile.png";
mediaUrl = "http://sample.com/CloudMusic/Music/0905/2575.mp3";
sDuration = "00:04:20";
songMoods = (
{
id = 3;
name = Sad;
noOfSongs = 0;
}
);
thumbUrl = "http://sample.com/CloudMusic/Images/sngfile.png";
title = "Aai Kale";
year = "";
}
)
What I want to do is chek for this artists array. How can I check for this artists coming as an array or just a string. Please help me.
Thanks
This will illustarate your problem
Get data rx in _recievedData then check the class of the object.
id object = [NSJSONSerialization
JSONObjectWithData:_recievedData
options:kNilOptions
error:&error];
if (error)
{
NSLog(#"Error in rx data:%#",[error description]);
}
if([object isKindOfClass:[NSString class]] == YES)
{
NSLog(#"String rx from server");
}
else if ([object isKindOfClass:[NSDictionary class]] == YES)
{
NSLog(#"Dictionary rx from server");
}
else if ([object isKindOfClass:[NSArray class]] == YES)
{
NSLog(#"Array rx from server");
}
This should help you.
id object = [responseData objectForKey:#"artists"];
if ([object isMemberOfClass:[NSString class]]) {
// do the stuff for NSString
}
else if ([object isMemberOfClass:[NSArray class]]) {
// do the stuff for NSArray
}

Resources