I have NSMutableArray data as below.
(
{
Id = "-1";
NameEn = Country;
},
{
Id = 14;
NameEn = Iran;
},
{
Id = 11;
NameEn = Jordan;
},
{
Id = 5;
NameEn = "United Arab Emirates";
},
{
Id = 4;
NameEn = "Suadi Arabia";
},
{
Id = 3;
NameEn = Kuwait;
},
{
Id = 10;
NameEn = Yemen;
},
{
Id = 6;
NameEn = Oman;
},
{
Id = 12;
NameEn = Syria;
},
{
Id = 7;
NameEn = Qatar;
},
{
Id = 13;
NameEn = Lebanon;
},
{
Id = 1;
NameEn = Egypt;
},
{
Id = 8;
NameEn = "Bahrain Kingdom";
}
)
I want to find the location where Id=5.
Any idea how can I do?
I tried with below.
NSString *myCountry = [[NSUserDefaults standardUserDefaults] valueForKey:#"mCountryId"];
NSUInteger indexOfTheObject = [feedsCountry indexOfObject: myCountry];
NSLog(#"indexOfTheObject===%i==%#", indexOfTheObject, myCountry);
if (NSNotFound == indexOfTheObject) {
NSLog(#"not found...");
}
But I get output as not found... for mCountryId as 5.
Use an NSDictionary instead, and key your entries by Id; e.g.:
NSMutableDictionary* dictionary = [NSMutableDictionary new];
[dictionary setObject:#"Egypt" forKey:#"1"];
// (etc...)
EDIT: If you already have an array and can not change that, use a for loop like this:
for(NSDictionary* entry in givenArray){
NSString* key = [entry objectForKey:#"Id"];
NSString* value = [entry objectForKey:#"NameEn"];
[dictionary setObject:value forKey:key];
}
NSPredicate * filter = [NSPredicate predicateWithFormat:#"Id = 5"];
NSArray * filtered = [array filteredArrayUsingPredicate:filter];
The first object in filtered is the dictionary with Id = 5
Related
I am storing my json response in a NSDictionary and this dictionary contains various array, so I want to replace all the null values with #"" empty string.
{
Specialities = (
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = (
{
AssetId = 157965;
BasePrice = 10000;
BookingAdvance = 100;
Currency = INR;
Details = "<null>";
DiscountedPrice = 9000;
Id = 16579;
IsBestOffer = 1;
IsPopular = 1;
LineItems = (
{
IconClass = "fa-check";
Text = "A DVD with all edited and unedited images";
}
);
PackageVersion = 123955;
PriceUnit = 3;
Quantity = 4;
SpecialityId = 22;
Status = Rejected;
Tags = (
53
);
TermsAndConditions = "<null>";
Title = Test;
}
);
Photos = (
157965,
157964
);
ServiceDescription = 43534;
Speciality = 22;
SpecialityName = "Wedding Photographer";
UserFRPs = (
{
AssetId = 157965;
CurrencyCode = INR;
DiscountedPrice = 800;
FRPId = 13;
Id = 4559;
Price = 1000;
SpecialityId = 22;
Status = Active;
},
{
AssetId = 565441;
CurrencyCode = INR;
DiscountedPrice = 9000;
FRPId = 18;
Id = 5559;
Price = 10000;
SpecialityId = 22;
Status = Active;
}
);
Videos = (
{
VideoId = DaWOguXZbNA;
VideoLink = "http://www.youtube.com/watch?v=DaWOguXZbNA";
VideoType = YouTube;
},
{
VideoId = DGVJtAHzzDQ;
VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
VideoType = YouTube;
},
{
VideoId = "_zxKLZR-xuk";
VideoLink = "http://www.youtube.com/watch?v=_zxKLZR-xuk";
VideoType = YouTube;
},
{
VideoId = 5SkBZcvuuQs;
VideoLink = "http://www.youtube.com/watch?v=5SkBZcvuuQs";
VideoType = YouTube;
},
{
VideoId = "H_Xi-lVB4Zw";
VideoLink = "http://www.youtube.com/watch?v=H_Xi-lVB4Zw";
VideoType = YouTube;
},
{
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 = (
157967
);
ServiceDescription = Ddhd;
Speciality = 37;
SpecialityName = "Hair and Makeup Stylist";
UserFRPs = (
{
AssetId = 157967;
CurrencyCode = INR;
DiscountedPrice = 900;
FRPId = 34;
Id = 4560;
Price = 1000;
SpecialityId = 37;
Status = Active;
}
);
Videos = (
{
VideoId = "onvkllwM-OI";
VideoLink = "http://www.youtube.com/watch?v=onvkllwM-OI";
VideoType = YouTube;
},
{
VideoId = "_-cRVdTW2s8";
VideoLink = "http://www.youtube.com/watch?v=_-cRVdTW2s8";
VideoType = YouTube;
},
{
VideoId = DGVJtAHzzDQ;
VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
VideoType = YouTube;
}
);
},
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = "<null>";
Photos = (
157963,
157962,
157961
);
ServiceDescription = Test;
Speciality = 55;
SpecialityName = Transport;
UserFRPs = "<null>";
Videos = (
{
VideoId = "cRchvv_dB2c";
VideoLink = "http://www.youtube.com/watch?v=cRchvv_dB2c";
VideoType = YouTube;
},
{
VideoId = "onvkllwM-OI";
VideoLink = "http://www.youtube.com/watch?v=onvkllwM-OI";
VideoType = YouTube;
},
{
VideoId = DGVJtAHzzDQ;
VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
VideoType = YouTube;
}
);
},
{
ApprovalStatus = Unapproved;
CurrencyCode = "<null>";
Packages = "<null>";
Photos = "<null>";
ServiceDescription = Baby;
Speciality = 5;
SpecialityName = "Children/Babies Photographer";
UserFRPs = "<null>";
Videos = (
{
VideoId = "cRchvv_dB2c";
VideoLink = "http://www.youtube.com/watch?v=cRchvv_dB2c";
VideoType = YouTube;
},
{
VideoId = DGVJtAHzzDQ;
VideoLink = "http://www.youtube.com/watch?v=DGVJtAHzzDQ";
VideoType = YouTube;
}
);
},
}
I want all null values to be replace by empty string.
Then just do that
NSString *json = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:0 error:nil] encoding: NSUTF8StringEncoding];
NSString *jsonWithoutNulls = [json stringByReplacingOccurrencesOfString:#"<null>" withString:#""];
NSData *data = [jsonWithoutNulls dataUsingEncoding:NSUTF8StringEncoding]
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
I prefer to use Macros to determine null values.
#define IS_NULL(value) (value != nil && value != Nil && value != NULL && value != (id)[NSNull null])
and I invoke it like
if (IS_NULL(CurrencyCode))
{
//insert ""
}else
{
//do necessary updates
}
OR you can also use the following method ,
-(BOOL) isNull: (NSString*)value{
if ([value isEqualToString:#"<null>"]){
return false;
}
return true;
}
and you can invoke it like,
if (isNull(currencyType))
{
//insert #""
}else{
//do necessary updates
}
Try this this is mine code i am using i hope it would be helpful!!
func checkDictionary(let dict:NSMutableDictionary)
{
let keys = Array(dict.allKeys)
for i in keys
{
let checkvalue = dict.valueForKey(i as! String)
if checkvalue! .isKindOfClass(NSNull)
{
dict.setObject("", forKey: i as! NSString)
}
else if checkvalue!.isKindOfClass(NSDictionary)
{
let dic = checkvalue as! NSDictionary
let dicts = dic.mutableCopy()
self.checkDictionary(dicts as! NSMutableDictionary)
dict.setObject(dicts, forKey: i as! NSString)
}
else if checkvalue! .isKindOfClass(NSArray)
{
let keys2 = checkvalue as! NSArray
let keys1 = keys2.mutableCopy() as! NSMutableArray
dict.setObject(keys1, forKey: i as! NSString)
for j in keys1
{
if j .isKindOfClass(NSNull)
{
keys1.replaceObjectAtIndex(keys1.indexOfObject(j), withObject:"")
}
if j.isKindOfClass(NSDictionary)
{
let dic = j as! NSDictionary
let dicts = dic.mutableCopy()
keys1.replaceObjectAtIndex(keys1.indexOfObject(j), withObject: dicts)
self .checkDictionary(dicts as! NSMutableDictionary)
}
}
}
}
}
In objective-C Try this!!
-(void)CheckDictionary:(NSMutableDictionary *)dic
{
NSArray *Arr = [dic allKeys];
for (int i = 0; i<Arr.count; i++)
{
if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSNull class]])
{
[dic setObject:#"" forKey:[Arr objectAtIndex:i]];
}
else if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dict = [[dic valueForKey:[Arr objectAtIndex:i]] mutableCopy];
[dic setObject:dict forKey:[Arr objectAtIndex:i]];
[self CheckDictionary:dict];
}
else if ([[dic valueForKey:[Arr objectAtIndex:i]] isKindOfClass:[NSMutableArray class]])
{
NSMutableArray *Arr12 = [dic valueForKey:[Arr objectAtIndex:i]];
for (int j = 0; j<Arr12.count; j++)
{
if ([[Arr12 objectAtIndex:j] isKindOfClass:[NSDictionary class]])
{
NSDictionary *dict123 = [Arr12 objectAtIndex:j];
NSMutableDictionary *dict = [dict123 mutableCopy];
[Arr12 replaceObjectAtIndex:j withObject:dict];
[self CheckDictionary:dict];
}
}
}
}
}
And Just pass the whole dictionary when you call this method I hope it would be helpful!!
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options: NSJSONReadingMutableContainers error: nil];
if (dictionary)
{
NSMutableDictionary *dict = [dictionary mutableCopy];
[self CheckDictionary:dict];
dictionary = [NSDictionary dictionaryWithDictionary:dict];
}
This is how we do it
#interface NSMutableArray (JSON)
- (void)recursivelyRemoveNulls;
#end
#implementation NSMutableArray (JSON)
- (void)recursivelyRemoveNulls
{
[self enumerateObjectsUsingBlock:^(id value, NSUInteger __unused idx, BOOL __unused *nestedStop)
{
if ([value isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *modifiedValue = [NSMutableDictionary dictionaryWithDictionary:value];
[modifiedValue recursivelyRemoveNulls];
[self removeObject:value];
[self addObject:modifiedValue];
}
else if ([value isKindOfClass:[NSArray class]])
{
NSMutableArray *modifiedValue = [NSMutableArray arrayWithArray:value];
[modifiedValue recursivelyRemoveNulls];
[self removeObject:value];
[self addObject:modifiedValue];
}
}];
}
#end
#interface NSMutableDictionary (JSON)
- (void)recursivelyRemoveNulls;
#end
#implementation NSMutableDictionary (JSON)
- (void)recursivelyRemoveNulls
{
[self enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL __unused *stop)
{
if (value == [NSNull null] || value == nil)
{
[self removeObjectForKey:key];
}
else if ([value isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *modifiedValue = [NSMutableDictionary dictionaryWithDictionary:value];
[modifiedValue recursivelyRemoveNulls];
self[key] = modifiedValue;
}
else if ([value isKindOfClass:[NSArray class]])
{
NSMutableArray *modifiedValue = [NSMutableArray arrayWithArray:value];
[modifiedValue recursivelyRemoveNulls];
self[key] = modifiedValue;
}
}];
}
#end
The short code you can use here:-
NSString * newValue=[self isNotNull:[your Object here]] ? [your Object here] : #"Value that you want to replace";
- (BOOL)isNull:(NSObject *)object {
if (!object) return YES;
else if (object == [NSNull null]) return YES;
else if ([object isKindOfClass:[NSString class]]) {
return ([((NSString *)object)isEqualToString : #""]
|| [((NSString *)object)isEqualToString : #"null"]
|| [((NSString *)object)isEqualToString : #"<null>"]
|| [((NSString *)object)isEqualToString : #"(null)"]
);
}
return NO;
}
- (BOOL)isNotNull:(NSObject *)object {
return ![self isNull:object];
}
Hi This is what am getting from server
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
4 = {
"display_name" = "ffd";
id = 4;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
}
i need to sort this based on "id" this is what am looking as output
Expecting output
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
4 = {
"display_name" = "ffd";
id = 4;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
}
This code i have tried and its not working
//vehiclesDictionary real dictionary
NSMutableArray *sortedKeys=[[NSMutableArray alloc]init];
for(NSString *item in [vehiclesDictionary allKeys]){
[sortedKeys addObject:[NSNumber numberWithInt:[item intValue]]];
}
NSArray *sortedKeysArray = [sortedKeys sortedArrayUsingSelector: #selector(compare:)];
NSLog(#"%#",sortedKeysArray);
NSMutableDictionary *sortedValues = [[NSMutableDictionary alloc] init];
for (NSString *key in sortedKeysArray) {
[sortedValues setValue:[vehiclesDictionary valueForKey:[NSString stringWithFormat:#"%#",key]] forKey:key];
}
NSLog(#"%#",sortedValues);
Pls help me
You cannot sort an NSDictionary, it is an unsorted collection type. You will need to store your keys in an array and sort this and use it to access the NSDictionary in order.
Based on your code above, it could be modified as follows, e.g.
NSDictionary *dict = [NSDictionary dictionary];
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
for (NSString *key in sortedKeys) {
NSLog(#"%#", [d objectForKey:key]);
// Do something with the object here
}
Here you can pass around the sortedKeys array with the NSDictionary, and use the sortedKeys array for in-order access to your NSDictionary.
A more concise approach to get the array, but with the same outcome as above, would be using:
NSDictionary -keysSortedByValueUsingComparator as shown here.
As others have mentioned, NSDictionaries cannot be sorted. However, you could do something like this:
-(NSArray *)sortedKeysFromDictionary:(NSDictionary *)dictionary ascending:(BOOL)ascending
{
/* get all keys from dictionary */
NSArray *allKeys = [dictionary allKeys];
NSString *key = #"id"; // using "id" as key here
/* sort keys */
NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:ascending];
return [NSArray arrayWithArray:[allKeys sortedArrayUsingDescriptors:#[dateDescriptor]]];
}
This will take all the keys from your dictionary, sort them in ascending or descending order as you desire and return that as an NSArray. This array can then be used to access the original dictionary. A sample implementation would look something like this:
for (NSString *key in [self sortedKeysFromDictionary:sampleDic ascending:NO])
{
/* get value from current key */
NSDictionary *currentDic = [sampleDic objectForKey:key];
}
in my project i applied the following code
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSLog(#" for ref id =%# ,name of diagnose=%# data is= %#",refidstr,diagnosedictforname ,diagnosisdict);
and the output in console is comes out as in the form
str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
};
}
);
response = 200;
}
ref id =3341 ,name of diagnose={
"diagnosis_name" = "TRANSIENT ISCHEMIA";
} data is= {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
}
now i just want to embed the values of both the Dictionaries into one dictionary
someone please help me to sort out this issue.
Make a mutable copy of the first dictionary:
NSMutableDictionary * mutDic = [dic1 mutableCopy];
and then:
[mutDic addEntriesFromDictionary:dic2];
Try this code:
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMutableDictionary *diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
NSDictionary *diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSArray *keys = [diagnosedictforname allKeys];
for (int i =0; i < keys.count; i++) {
NSString *key = [keys objectAtIndex:i];
[diagnosisdict setValue:[diagnosedictforname valueForKey:key] forKey:key];
}
NSLog(#"your dic -> %#", diagnosisdict);
I have a NSArray of NSDictionary objects:
[
{
id = 1;
fromDate = 2014-04-03;
toDate = 2014-04-05;
date = 0000-00-00;
title = title 1
},
{
id = 1;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-04-03
title = title 1
},
{
id = 1;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-04-04;
title = title 1
},
{
id = 2;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-05-10;
title = title 2
},
{
id = 2;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-05-11;
title = title 2
}
]
I would like to merge dictionaries with same id value into one dictionary combining all date, fromDate and toDate keys, obtaining an array like this, that ignores zero values:
[
{
id = 1,
combinedDates = 2014-04-03, 2014-04-05, 2014-04-03, 2014-04-04;
title = title 1
},
{
id = 2,
combinedDates = 2014-05-10, 2014-05-11;
title = title 2
}
]
Can someone point me to the right direction?
I don't know of any way to do this other than basic brute force:
-(NSArray*)combinedArray:(NSArray*)array
{
NSMutableArray* combined = [NSMutableArray new];
// Iterate over each unique id value
for(id key in [NSSet setWithArray:[array valueForKeyPath:#"id"]])
{
// skip missing keys
if([key isKindOfClass:[NSNull class]])
continue;
// Sub array with only id = key
NSArray* filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary* evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject valueForKey:#"date"] && [[evaluatedObject valueForKey:#"id"] isEqual:key];
}]];
// Grab the dates
NSArray* dates = [filtered valueForKeyPath:#"date"];
// add the new dictionary
[combined addObject:#{ #"id":key, #"combinedDates":dates }];
}
return array;
}
// Group By id
-(NSMutableDictionary*)combinedArray:(NSArray*)array
{
NSMutableArray *categories = [[NSMutableArray alloc] init];
for (NSDictionary *data in array) {
NSString *category = [data valueForKey:#"id"];
if (![categories containsObject:category]) {
[categories addObject:category];
}
}
NSMutableDictionary *categoryData = [[NSMutableDictionary alloc]init];
for (NSString *strCat in categories) {
NSMutableArray *catArray = [[NSMutableArray alloc]init];
for (NSDictionary *data in array) {
NSString *category = [data valueForKey:#"id"];
if ([category isEqualToString:strCat]) {
[catArray addObject:data];
}
}
[categoryData setObject:catArray forKey:strCat];
}
return categoryData;
}
I have a NSArray which looks like this:
#[#"file1", #"directory/testfile", #"directory/otherdir/testfile", #"otherdir/", #"otherdir/otherfile"]
And I'm trying to convert it to a NSDictionary which looks like this:
#{
#"directory/":#{
#"otherdir/":#{
#"testfile":[..some array with data..]}
},
#"testfile":[..some array with data..]
},
#"otherdir/":#{
#"otherfile":[..some array with data..]
},
#"file1":[..some array with data..]
}
Basically, a NSDictionary which looks like a file tree. Thanks in advance!
EDIT: The actual array I have is this:
(
"blog/",
"blog/code.css",
"blog/style.css",
"etc/",
"etc/awsservices.png",
"etc/speeds.png",
"etc/test/",
"etc/test/other/",
"etc/test/other/speeds.png",
"site/",
"site/dino.png",
"site/error.css",
"site/main.css",
"site/signet.min.js"
)
And the code I wrote for this:
-(NSDictionary*)buildDictionaryWithContentsOfPath:(NSMutableArray*)files {
NSString *subDir;
NSMutableDictionary *returnable = [[NSMutableDictionary alloc] initWithDictionary:#{}];
BOOL directory;
NSLog(#"%#", files);
for (S3ObjectSummary *objectSummary in files) {
if ([[objectSummary key] hasSuffix:#"/"]) {
if (subDir && [[objectSummary key] hasPrefix:subDir]) {
NSLog(#"prefixed %#", [objectSummary key]);
NSMutableDictionary *treeDict = [[NSMutableDictionary alloc] initWithDictionary:#{}];
[returnable[subDir] setObject:treeDict forKey:[objectSummary key]];
} else {
subDir = [objectSummary key];
NSLog(#"dir %#", [objectSummary key]);
NSMutableDictionary *treeDict = [[NSMutableDictionary alloc] initWithDictionary:#{}];
[returnable setObject:treeDict forKey:[objectSummary key]];
}
directory = true;
} else {
S3GetObjectMetadataRequest *getMetadataRequest = [[S3GetObjectMetadataRequest alloc] initWithKey:[objectSummary key] withBucket:self.bucket.name];
S3GetObjectMetadataResponse *getMetadataResponse = [self.client getObjectMetadata:getMetadataRequest];
if (![[objectSummary key] hasPrefix:subDir]) {
NSLog(#"file %#",[objectSummary key]);
[returnable setObject:#{#"filename":[objectSummary key], #"directory":#(directory), #"created_at":getMetadataResponse.lastModified} forKey:[objectSummary key]];
} else {
for (NSString __strong *pathComp in [[objectSummary key] pathComponents]) {
pathComp = [NSString stringWithFormat:#"%#/", pathComp];
NSLog(#"path component %#", pathComp);
if (![[objectSummary key] hasSuffix:#"/"]) {
if (returnable[pathComp]) {
NSLog(#"has comp %#", pathComp);
[returnable[pathComp] setObject:#{#"filename":[objectSummary key], #"directory":#(directory), #"created_at":getMetadataResponse.lastModified} forKey:[objectSummary key]];
}
}
}
}
directory = false;
}
//[self.fileTree addObject:#{#"filename":[objectSummary key], #"directory":#(directory), #"created_at":getMetadataResponse.lastModified}];
}
return returnable;
}
And the dictionary it returns:
{
"blog/" = {
"blog/code.css" = {
"created_at" = "2013-12-07 12:13:37 +0000";
directory = 0;
filename = "blog/code.css";
};
"blog/style.css" = {
"created_at" = "2013-12-07 12:13:36 +0000";
directory = 0;
filename = "blog/style.css";
};
};
"etc/" = {
"etc/awsservices.png" = {
"created_at" = "2013-12-07 12:26:37 +0000";
directory = 0;
filename = "etc/awsservices.png";
};
"etc/speeds.png" = {
"created_at" = "2013-12-07 13:29:27 +0000";
directory = 0;
filename = "etc/speeds.png";
};
// PROBLEM HERE
"etc/test/" = {
};
"etc/test/other/" = {
};
"etc/test/other/speeds.png" = {
"created_at" = "2013-12-07 17:29:21 +0000";
directory = 0;
filename = "etc/test/other/speeds.png";
};
// PROBLEM HERE
};
"site/" = {
"site/dino.png" = {
"created_at" = "2013-12-07 12:13:59 +0000";
directory = 0;
filename = "pmerino/dino.png";
};
"site/error.css" = {
"created_at" = "2013-12-07 12:13:59 +0000";
directory = 0;
filename = "pmerino/error.css";
};
"site/main.css" = {
"created_at" = "2013-12-07 12:13:59 +0000";
directory = 0;
filename = "pmerino/main.css";
};
"site/signet.min.js" = {
"created_at" = "2013-12-07 12:13:59 +0000";
directory = 0;
filename = "pmerino/signet.min.js";
};
};
}
As you can see, this part:
"etc/test/" = {
};
"etc/test/other/" = {
};
"etc/test/other/speeds.png" = {
"created_at" = "2013-12-07 17:29:21 +0000";
directory = 0;
filename = "etc/test/other/speeds.png";
};
Should look like this:
"etc/" = {
"test/" = {
"other/" = {
"speeds.png" = {
"created_at" = "2013-12-07 17:29:21 +0000";
directory = 0;
filename = "etc/test/other/speeds.png";
};
};
};
};
If I understand your problem correctly, this method should be helpful:
// Add the path to the tree. Returns the "node" for this path.
-(NSMutableDictionary *)addFile:(NSString *)path toTree:(NSMutableDictionary *)tree
{
NSMutableDictionary *node = tree;
// Split path into components:
NSArray *components = [path componentsSeparatedByString:#"/"];
// Create all intermediate dictionaries:
for (NSUInteger i = 0; i < [components count] - 1; i++) {
NSString *key = [components[i] stringByAppendingString:#"/"];
if (node[key] == nil) {
node[key] = [NSMutableDictionary dictionary];
}
node = node[key];
}
// Process last component, which is the file name,
// or "" in the case of a dictionary:
NSString *name = [components lastObject];
if ([name length] > 0) {
node[name] = [NSMutableDictionary dictionary];
node = node[name];
}
return node;
}
If you use it like this:
NSArray *files = ...; // Your array of files
NSMutableDictionary *tree = [NSMutableDictionary dictionary];
for (NSString *path in files) {
NSMutableDictionary *node = [self addFile:path toTree:tree];
BOOL isDir = [path hasSuffix:#"/"];
if (!isDir) {
node[#"filename"] = path;
}
}
the resulting dictionary is
{
"blog/" = {
"code.css" = {
filename = "blog/code.css";
};
"style.css" = {
filename = "blog/style.css";
};
};
"etc/" = {
"awsservices.png" = {
filename = "etc/awsservices.png";
};
"speeds.png" = {
filename = "etc/speeds.png";
};
"test/" = {
"other/" = {
"speeds.png" = {
filename = "etc/test/other/speeds.png";
};
};
};
};
"site/" = {
"dino.png" = {
filename = "site/dino.png";
};
"error.css" = {
filename = "site/error.css";
};
"main.css" = {
filename = "site/main.css";
};
"signet.min.js" = {
filename = "site/signet.min.js";
};
};
}