Iam trying to create a plist with following feature.
Inside plist there are two keys
1.id
2.status
current values are id:91 status:buy here Id should be unique .Means if i tried to add a 3rd entry like id:91 status:downlaod .Then it should replace the existing 91 and status:buy with new one.
please help me
check below image
How can i remove the status and id if i got one match in Id?
Enumerate root array and compare id value in dictionary
NSMutableArray *rootArray = [[NSMutableArray alloc] initWithCapacity:0];
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:#"91",#"id",#"Buy",#"status",nil];
NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:#"92",#"id",#"Download",#"status",nil];
[rootArray addObject:dic];
[rootArray addObject:dic1];
NSDictionary *dic3 = [[NSDictionary alloc] initWithObjectsAndKeys:#"91",#"id",#"Download",#"status",nil];
NSDictionary *foundMatch =nil;
for(NSDictionary *dictionary in rootArray)
{
if ([[dictionary objectForKey:#"id"] isEqualToString:[dic3 objectForKey:#"id"]]) {
foundMatch = dictionary;
break;
}
}
if (foundMatch!=nil) {
[rootArray removeObject:foundMatch];
[rootArray addObject:dic3];
}
else {
[rootArray addObject:dic3];
}
[rootArray writeToFile:#"path" atomically:YES];
It is .plist file which has array of dictionary and each dictionary has two key
id
status
I give you official documentation for How to create plist file programmatically.
Related
How to convert an array into a dictionary in Objective-C language?
This is the array:
[{"1":"2"}, {"2":"3"}]
But I want :
{"1":"2", "2":"3"}
Please help me, I am a new iPhone developer.
I am assuming that you want to combine an array of dictionaries into a single dictionary.
NSArray *array = #[#{#"1":#"2"},#{#"2":#"3"}];
NSMutableDictionary *result = [[NSMutableDictionary alloc]init];
for (NSDictionary *dict in array)
{
[result addEntriesFromDictionary:dict];
}
/*
result = {
1 = 2;
2 = 3;
}
*/
Where did your data come from? The easiest way to "convert" the above is to simply create a single dictionary in the first place.
Otherwise:
NSMutableDictionary* newDict = [NSMutableDictionary dictionary];
for (NSDictionary* oldDict in sourceArray) {
[newDict addEntriesFromDictionary:oldDict];
}
I am very new to Objective-C and iOS programming so be gentle :)
I am trying to add an nsmutabledictionary to and nsmutablearray. I am succeeding but not with the results I was hoping for. Here is my code :
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
[dictionary setValue:#"lat1" forKey:#"lat"];
[dictionary setValue:#"long1" forKey:#"long"];
[dictionary setValue:#"alt1" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
[dictionary setValue:#"lat2" forKey:#"lat"];
[dictionary setValue:#"long2" forKey:#"long"];
[dictionary setValue:#"alt2" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
NSLog(#"%#",array);
NSLog(#"%lu",(unsigned long)[array count]);
Here is the NSLog output:
2014-06-05 10:29:27.377 dicttest[4863:60b] (
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
},
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
}
)
2014-06-05 10:29:27.386 dicttest[4863:60b] 2
Here is what I was hoping to achieve:
2014-06-05 10:29:27.377 dicttest[4863:60b] (
{
messages = {
alt = alt1;
lat = lat1;
long = long1;
};
},
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
}
)
2014-06-05 10:29:27.386 dicttest[4863:60b] 2
If I the dictionary straight to the array (instead of add the dictionary to messages and then adding that to the array) then I get the output I am looking for. Can somebody explain to me exactly what I am doing wrong?
It looks to me like you want:
An array
At index 0:
A dictionary with a single key "messages"
A dictionary with keys "alt", "lat", and "long"
At index 1:
A dictionary with a single key "messages"
A dictionary with keys "alt", "lat", and "long"
The data in the second array entry should use the same keys, but different data. As the others have pointed out, your mistake is using a single dictionary "dictionary"
When you add an object to a collection like a dictionary or array, the collection holds a pointer to the object, not a copy of the object. If you add the same object to a collection more than once, you have 2 pointers to the same object, not 2 unique objects.
When you add your "dictionary" object, to your structure, change it, and add it again, you are not getting the result you expect because both entries in your structure point to a single dictionary. When you change the values, it changes in both places.
The same goes for your "messages" dictionary. You need 2 of those as well.
Fix your code by adding new dictionaries, dictionary2 and messages2:
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dictionary2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages2 = [[NSMutableDictionary alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
[dictionary setValue:#"lat1" forKey:#"lat"];
[dictionary setValue:#"long1" forKey:#"long"];
[dictionary setValue:#"alt1" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
[dictionary2 setValue:#"lat2" forKey:#"lat"];
[dictionary2 setValue:#"long2" forKey:#"long"];
[dictionary2 setValue:#"alt2" forKey:#"alt"];
[messages2 setObject: dictionary2 forKey:#"messages"];
[array addObject: messages2];
NSLog(#"%#",array);
NSLog(#"%lu",(unsigned long)[array count]);
You might also look at using object literal syntax, e.g.:
dictionary[#"lat"] = #"lat1";
dictionary[#"long"] = #"long1";
dictionary[#"alt"] = #"alt1";
messages[#"messages"] = dictionary;
If you didn't need the whole thing to be mutable, you could even do everything with one line:
NSMutableArray *array = [
#[
#{#"messages": #{#"lat": #"lat1", #"long": #"long1", #"alt": #"alt1"}},
#{#"messages": #{#"lat": #"lat2", #"long": #"long2", #"alt": #"alt2"}}
];
Or to make it mutable:
NSMutableArray *array = [
#[
[#{#"messages":
[#{#"lat": #"lat1", #"long": #"long1", #"alt": #"alt1"} mutableCopy]} mutableCopy],
[#{#"messages":
[#{#"lat": #"lat2", #"long": #"long2", #"alt": #"alt2"} mutableCopy]} mutableCopy]
] mutableCopy];
EDIT: to add contents dynamically, you could use a method like this: (assuming that array is an instance variable)
- (void) addMessageWithLat: (NSString *) latString
long: (NSString *) longString
alt: (NSString *) altString;
{
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSDictonary *contents =
[#{#"lat": latString,
#"long": longString,
#"alt": altString}
mutableCopy];
messages[#"messages"] = contents;
[array addObject: messages];
}
The problem is that you are making adding the new values in the same object reference. So the new Value will replace the older one. Just add this line before [dictionary setValue:#"lat2" forKey:#"lat"];
dictionary = [NSMutableDictionary alloc]init];
and this line before the second instance of [messages setObject:dictionary forKey:#"messages"];
messages = [[NSMutableDictionary alloc] init];
We have an app that calls a SOAP web service and retrieves a long list of XML, which the app then parses into an NSArray of NSDictionary objects. The NSArray contains a list of Rental Apartment information, each of which is stored into an NSDictionary.
The entire list may contain 10 different types of Apartments (i.e. 2-room, 3-room), and we need to split the NSArray into smaller NSArrays based on Room-Type, which has the key "roomType" in the NSDictionary objects.
Currently our algorithm is
Use [NSArray valueForKeyPath:#"#distinctUnionofObjects.room-type"]
to obtain a list of unique room-type values.
Loop through the list of unique room-type values
For each unique room-type value, use NSPredicate to retrieve matching items from the Original list
Our code is below (renamed for clarity):
NSArray *arrOriginal = ... ...; // Contains the Parsed XML list
NSMutableArray *marrApartmentsByRoomType = [NSMutableArray arrayWithCapacity:10];
NSMutableArray *arrRoomTypes = [arrOriginal valueForKeyPath:#"distinctUnionOfObjects.roomType"];
for(NSString *strRoomType in arrRoomTypes) {
NSPredicate *predicateRoomType = [NSPredicate predicateWithFormat:#"roomType=%#", strRoomType];
NSArray *arrApartmentsThatMatchRoomType = [arrOriginal filteredArrayUsingPredicate:predicateRoomType]; // TAKES A LONG TIME EACH LOOP-ROUND
[marrApartmentsByRoomType addObject:arrApartmentsThatMatchRoomType];
}
However, step 3 is taking a long time as the original list may contain large amount (>100,000) of items. It seems that NSPredicate goes through the entire list for each key value. Is there a more efficient way of splitting a large NSArray into smaller NSArrays, based on NSDictionary keys?
If the order of your splited Arrays is not important, i have a solution for you:
NSArray *arrOriginal;
NSMutableDictionary *grouped = [[NSMutableDictionary alloc] initWithCapacity:arrOriginal.count];
for (NSDictionary *dict in arrOriginal) {
id key = [dict valueForKey:#"roomType"];
NSMutableArray *tmp = [grouped objectForKey:key];
if (tmp == nil) {
tmp = [[NSMutableArray alloc] init];
[grouped setObject:tmp forKey:key];
}
[tmp addObject:dict];
}
NSMutableArray *marrApartmentsByRoomType = [grouped allValues];
This is quite performant
- (NSDictionary *)groupObjectsInArray:(NSArray *)array byKey:(id <NSCopying> (^)(id item))keyForItemBlock
{
NSMutableDictionary *groupedItems = [NSMutableDictionary new];
for (id item in array) {
id <NSCopying> key = keyForItemBlock(item);
NSParameterAssert(key);
NSMutableArray *arrayForKey = groupedItems[key];
if (arrayForKey == nil) {
arrayForKey = [NSMutableArray new];
groupedItems[key] = arrayForKey;
}
[arrayForKey addObject:item];
}
return groupedItems;
}
Improving #Jonathan answer
Converting array to dictionary
Maintaining the same order as it was in original array
//only to a take unique keys. (key order should be maintained)
NSMutableArray *aMutableArray = [[NSMutableArray alloc]init];
NSMutableDictionary *dictFromArray = [NSMutableDictionary dictionary];
for (NSDictionary *eachDict in arrOriginal) {
//Collecting all unique key in order of initial array
NSString *eachKey = [eachDict objectForKey:#"roomType"];
if (![aMutableArray containsObject:eachKey]) {
[aMutableArray addObject:eachKey];
}
NSMutableArray *tmp = [grouped objectForKey:key];
tmp = [dictFromArray objectForKey:eachKey];
if (!tmp) {
tmp = [NSMutableArray array];
[dictFromArray setObject:tmp forKey:eachKey];
}
[tmp addObject:eachDict];
}
//NSLog(#"dictFromArray %#",dictFromArray);
//NSLog(#"Unique Keys :: %#",aMutableArray);
//Converting from dictionary to array again...
self.finalArray = [[NSMutableArray alloc]init];
for (NSString *uniqueKey in aMutableArray) {
NSDictionary *aUniqueKeyDict = #{#"groupKey":uniqueKey,#"featureValues":[dictFromArray objectForKey:uniqueKey]};
[self.finalArray addObject:aUniqueKeyDict];
}
Hope, It will help when client wants final array in same order as input array.
NSMutableDictionary *expense_ArrContents = [[NSMutableDictionary alloc]init];
for (int i = 1; i<=4; i++) {
NSMutableArray *current_row = [NSMutableArray arrayWithObjects:#"payer_id",#"Expense_Type_id",#"Category_Id",#"SubCategory_Id",nil];
[expense_ArrContents setObject:current_row forKey: [NSNumber numberWithInt:i]];
}
NSArray *newArray = [expense_ArrContents allKeysForObject:#"payer_id"];
NSLog(#"%#",[newArray description]);
i want to get the list of key values containing the particular object which is in the array of values stored in nsmutabledictionary for a particular key.
In the line where you get all the keys ([expense_ArrContents allKeysForObject:#"payer_id"];) you actually get keys for an object that is not in any of the array's items. This #"player_id" is different object than the #"player_id" you added in current_row. In fact, maybe all of your rows have different #"player_id" objects (except if the compiler has made some optimization - maybe it threats that same string literal as one object instead of creating new object for each iteration).
Try creating an NSString object for the #"player_id" which you add to the current_row and then get all the keys for that same object:
NSString* playerId = #"player_id";
for(){
NSMutableArray *current_row = [NSMutableArray arrayWithObjects: playerId,...];
...
}
NSArray *newArray = [expense_ArrContents allKeysForObject:playerId];
Your NSArray *newArray = [expense_ArrContents allKeysForObject:#"payer_id"]; will not return any value because in expense_ArrContents there is no such key(#"payer_id"), instead there are keys like 1,2,3 etc.What is your requirement?Want to see what all keys are there in expense_ArrContents just log
NSArray*keys=[expense_ArrContents allKeys];
Try this :
NSMutableArray *array_key=[[NSMutableArray alloc]init];
for (NSString *key in expense_ArrContents) {
if ([[expense_ArrContents objectForKey:key] containsObject:#"payer_id"]) {
[array_key addObject:key];
}
}
I am new to iOS and want to create an NSArray like this which contains an NSDictionary.
[
{
Image: 1, 2,3
Title: 1,2,3
Subtitle:1,2,3
}
]
I have tried this.
NSArray *obj-image=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *obj-title=#[#"Test",#"Test",#"Test"];
NSArray *obj-subtitle=#[#"Test",#"Test",#"Test"];
NSDictionary * obj_dictionary ={ image : obj_image, title:obj_title, subtitle:obj_subtitle}
NSArray * obj_array= [obj_dictionarry];
But not working and how to access them.
First of all, you initialization of Arrays and Dictionaries is wrong. You cannot use "-" in the names, period.
Second, you need to allocate and then initialize the objects. This is how you do that with arrays:
NSArray *images = [NSArray arrayWithObjects: #"TestImage",#"TestImage",#"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: #"TestTitle",#"TestTitle",#"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: #"TestSubTitle",#"TestSubTitle",#"TestSubTitle",nil];
Then you need Mutable dictionary and mutable arrays to work with the data (mutable means you can change the values inside, add or remove objects etc.)
This is the most basic example of what you are trying to achieve:
NSArray *images = [NSArray arrayWithObjects: #"TestImage",#"TestImage",#"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: #"TestTitle",#"TestTitle",#"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: #"TestSubTitle",#"TestSubTitle",#"TestSubTitle",nil];
NSMutableArray *objectsMutable = [[NSMutableArray alloc] init];
for (NSString *string in images) {
NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc] init];
[dictMutable setObject:string forKey:#"image"];
//determining the index of the image
NSInteger stringIndex = [images indexOfObject:string];
[dictMutable setObject:[titles objectAtIndex:stringIndex] forKey:#"title"];
[dictMutable setObject:[subtitles objectAtIndex:stringIndex] forKey:#"subtitle"];
NSDictionary *dict = [[NSDictionary alloc] init];
dict = dictMutable;
[objectsMutable addObject:dict];
}
NSArray *objects = objectsMutable;
NSLog(#"%#", objects);
Hope this helps.
As you can see, I'm going through the images array, capturing the index of each one, an then just apply values of other arrays from the same index into a mutable dictionary.
All I do after that is just make a regular dictionary and array to put the data inside. This is ho the Log will look:
(
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
}
)
You have an array with three objects inside, each with their own image, title and subtitle.
Here is code :
NSMutableArray *array = [[NSMutableArray alloc] init];
NSMutableDictionary *mdict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"object1",#"key1",#"object2",#"key2",nil];
[array addObject:mDict];
so now if u need to access dictionary from array then :
NSMutableDictionary *mDict1 = [array objectatindex:0];
NSLog(#"%#",[mDict1 valueForkey:#"key1"];
--> print object 1.
This is the way to store array of dictionaries:
NSDictionary *dic=#{#"kishore":#"hai"};
NSMutableArray *arr=[[NSMutableArray alloc]init];
[arr addobject:dic];
this is the way to get those values:
[arr objectforkeyValue #"kishore"];
NSMutableArray *dictArray = [[NSMutableArray alloc] init]; // created and initiated mutable array
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; // created and initiated mutable Dictionary
[dict setObject:#"object1" forKey:#"1"]; // added a key pair in dictionary (you can set multiple objects)
[dictArray addObject:dict]; // added dictionary to array (you can add multiple dictionary to array )
NSLog(#"dictionary inside an array : %#",dictArray[0][#"1"]); // access dictionary from array
You can try something like this
[NSArray arrayWithObjects:#{#"Image":#[#1,#2,#3]},#{#"Title":#[#1,#2,#3]},#{#"SubTitle":#[#1,#2,#3]}, nil];
You can easily create objects of array and access them back using following way.
NSArray *objimage=#[#"Test1.png",#"Test2.png",#"Test3.png"];
NSArray *objtitle=#[#"Test1",#"Test2",#"Test3"];
NSArray *objsubtitle=#[#"Test1",#"Test2",#"Test3"];
NSDictionary *obj_dictionary = #{#"image":objimage,#"Title":objtitle, #"subtitle":objsubtitle};
NSArray * obj_array= [[NSArray alloc] initWithObjects:obj_dictionary, nil]; // Create Array of nested objects
if([obj_array count] > 0) {
NSArray * imageArray = obj_array[0][#"image"]; // Access the nested objects in Array.
NSLog(#"%#", imageArray[0]);
}
first of all u need to declare correct variable name
NSArray *objImage=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *objTitle=#[#"Test",#"Test",#"Test"];
NSArray *objSubtitle=#[#"Test",#"Test",#"Test"];
at this point all u are created all the array, and u need to create dictionary like below
NSDictionary *obj_dictionary = #{#"image":objImage,#"title":objTitle, #"subtitle":objSubtitle};
// NSArray * obj_array = obj_dictionary[#"image"];
NSArray * obj_array = #[obj_dictionary]; //u can crate array of dictionary like this
in above obj_dictionary will contains all the array like below,
Title = (
Test,
Test,
Test
);
image = (
"Test.png",
"Test.png",
"Test.png"
);
subtitle = (
Test,
Test,
Test
);
and u can access the object in the dictionary like below using a key for example
NSArray * obj_array_images = obj_dictionary[#"image"];
gives an array of images that is associated with key image, similarly u can access other array like this by providing different keys associated with the dictionary obj_dictionary for example
NSArray * obj_array_titles = obj_dictionary[#"title"];
NSArray * obj_array_subtitles = obj_dictionary[#"subtitle"];
edit
NSArray *objImage=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *objTitle=#[#"Test",#"Test",#"Test"];
NSArray *objSubtitle=#[#"Test",#"Test",#"Test"];
NSDictionary *obj_dictionary = #{#"image":objImage,#"title":objTitle, #"subtitle":objSubtitle};
// NSArray * obj_array = obj_dictionary[#"image"];
NSArray * obj_array = #[obj_dictionary]; //u can crate array of dictionary like this