i am trying to catch some data on my plist , it has a lot of records
for that case i used this code
NSString *path = [[NSBundle mainBundle] pathForResource:#"kurdiebg" ofType:#"plist"];
NSArray *plistData = [NSArray arrayWithContentsOfFile:path];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"english = %#", self.searchQwery.text];
NSArray *filtered = [plistData filteredArrayUsingPredicate:filter];
NSLog(#"found matches: %# : %#", filtered,[filtered valueForKey:#"kurdi"]);
NSString*nss = [NSString stringWithFormat:#"%#",[filtered valueForKey:#"english"]];
self.lblWord.text = nss;
its all fine on the Log, but on the uilabel it returns this
on the NSLog
Thanks
your filter is array od NSdictionary
NSString *path = [[NSBundle mainBundle] pathForResource:#"kurdiebg" ofType:#"plist"];
NSArray *plistData = [NSArray arrayWithContentsOfFile:path];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"english = %#", self.searchQwery.text];
NSArray *filtered = [plistData filteredArrayUsingPredicate:filter];
NSLog(#"found matches: %# : %#", filtered,[filtered valueForKey:#"kurdi"]);
NSString*nss = [NSString stringWithFormat:#"%#",[filtered valueForKey:#"english"]];
if (filtered.count>0) {
NSDictionary *dic = filtered[0];
self.lblWord.text = dic[#"english"];
}
Related
This question already has answers here:
How To Add New Keys and Values Into Plist Using Objective C?
(1 answer)
Save NSDictionary to plist
(3 answers)
Closed 7 years ago.
I have created JSON data store Into Plist. Now the problem is after JSON data storage, I need to add two set of keys into every array of dictionary items like below Image_2.The key name isParent - Boolean YES and isChild - Boolean YES with levels like mentioned below Image_2.
Now I have below structure of plsit datas Its perfectly working by below code.
I need to add two keys for outside of object subjectcount and inside of objectsubjectcount red marked datas.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = JSON[#"response"];
NSArray *keys = [response allKeys];
NSMutableArray *objects = [NSMutableArray new];
for (NSString *key in keys) {
NSMutableDictionary *object = response[key];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"subject = %#",object[#"subject"]];
NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
NSInteger subjects = [object[#"subject"] integerValue];
if (subjects > 0) {
NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
for (NSInteger i = 0; i < subjects; i++) {
[Objects_Subjectcount addObject:object];// object or anything you need
}
}
[objects addObject:object];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"File.plist"];
NSError *writeError = nil;
NSDictionary *finalDict = #{#"Objects": objects};
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(#"Error in saveData: %#", error);
}
NOTE : all the datas store by JSON but after storage need to add additional values by manually! Thats I am trying
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListMutable error:&writeError];
Retrieve data from plist like this.
NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
Now suppose you want to update first array of dictionary then
NSMutableArray *array = [[NSMutableArray alloc]init:[plistDic objectAtIndex:0]]
You can do for loop if you want to change all array data...Right i am just using first object data..
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init:[array objectAtIncex:0]];
[dict addObject:"yourdata" forKey:"yourkey"];
[array replaceObject:dict atIndex:0];
[plistDic replaceObjectAtIndex:0 withObject:array];
And last
[plistDic writeToFile:plistPath atomically:YES];
The object from response[key] is immutable so it can't be modified as below:
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
Making it mutable as below, it can be modified by any method add/remove/set.
NSMutableDictionary *object = [response[key] mutableCopy];
Hope using below modified block, you would see required changes.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = JSON[#"response"];
NSArray *keys = [response allKeys];
NSMutableArray *objects = [NSMutableArray new];
for (NSString *key in keys) {
NSMutableDictionary *object = [response[key] mutableCopy];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"subject = %#",object[#"subject"]];
NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
NSInteger subjects = [object[#"subject"] integerValue];
if (subjects > 0) {
[object setObject:#"" forKey:#"level"];
[object setObject:#(YES) forKey:#"isParent"];
NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
for (NSInteger i = 0; i < subjects; i++) {
[Objects_Subjectcount addObject:#{#"level":#(0), #"isChild":#(YES)}];
}
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
}
[objects addObject:object];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"File.plist"];
NSError *writeError = nil;
NSDictionary *finalDict = #{#"Objects": objects};
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(#"Error in saveData: %#", error);
}
I have stored JSON data Into within Plist. Whenever I want to see my stored data I am taking path details and find into my machine then only I can see. I need to read data after storage using objective C.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = JSON[#"response"];
NSArray *keys = [response allKeys];
NSMutableArray *objects = [NSMutableArray new];
for (NSString *key in keys) {
NSMutableDictionary *object = response[key];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"subject = %#",object[#"subject"]];
NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
NSInteger subjects = [object[#"subject"] integerValue];
if (subjects > 0) {
NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
for (NSInteger i = 0; i < subjects; i++) {
[Objects_Subjectcount addObject:object];// object or anything you need
}
}
[objects addObject:object];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"File.plist"];
NSError *writeError = nil;
NSDictionary *finalDict = #{#"Objects": objects};
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(#"Error in saveData: %#", error);
}
Once you have the right path to the plist file, you can read it by:
NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
int value = [[plistDic objectForKey:#”value”] intValue]; //to get a int value for value for example
and to write to plist:
[plistDic setObject:[NSNumber numberWithInt:2] forKey:#”value”];
[plistDic writeToFile: path atomically:YES];
Try this:
NSError *error = nil;
NSData * tempData = [[NSData alloc] initWithContentsOfFile:#"File.plist"];
NSPropertyListFormat plistFormat = nil;
NSDictionary *temp = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NSPropertyListXMLFormat_v1_0 error:&error];
Note :
when you read data using NSPropertyListSerialization you dont have to pass NSPropertyListFormat . you either pass nil or pass the address for NSPropertyListFormat.
Hope this will help.
I have an NSArray with NSDictionary inside. It looks like:
etc.
I need to sort it by date inside NSDictionary. I need something like this:
How can I do this? Here is my method which gives me first unsorted array:
- (void)iterateOverDocumentsDirectory
{
arrayWithFiles = [NSMutableArray new];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirPath = [paths objectAtIndex:0];
NSString *finalPathToFolder = [NSString stringWithFormat:#"%#/", documentsDirPath];
albumNames = [[fileManager contentsOfDirectoryAtPath:finalPathToFolder error:&error] mutableCopy];
if (albumNames == nil) {
// error...
}
for (NSString *album in albumNames)
{
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:album forKey:#"name"];
NSString *finalPathToFiles = [NSString stringWithFormat:#"%#/%#", documentsDirPath, album];
NSArray *tempArray = [fileManager contentsOfDirectoryAtPath:finalPathToFiles error:&error];
NSMutableArray *arrayWithEachFiles = [NSMutableArray new];
for (NSString *tempString in tempArray)
{
NSMutableDictionary *eachFileDict = [[NSMutableDictionary alloc] init];
NSString *pathToFile = [NSString stringWithFormat:#"%#/%#/%#", documentsDirPath, album, tempString];
[eachFileDict setValue:pathToFile forKey:#"path"];
NSDictionary *filePathsArray1 = [[NSFileManager defaultManager] attributesOfItemAtPath:pathToFile error:nil];
NSDate *modifiedDate = [filePathsArray1 objectForKey:NSFileCreationDate];
[eachFileDict setValue:modifiedDate forKey:#"date"];
[arrayWithEachFiles addObject:eachFileDict];
}
NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:YES];
NSArray *sortDescriptors = #[ageDescriptor];
NSArray *sortedArrayWithFiles = [[arrayWithEachFiles sortedArrayUsingDescriptors:sortDescriptors] mutableCopy];
[tempDict setValue:sortedArrayWithFiles forKey:#"files"];
[arrayWithFiles addObject:tempDict];
}
}
Use following code for sorting the array of dictionaries:
NSArray * sortedArray = [myArray sortedArrayUsingComparator:^(id obj1, id obj2) {
NSNumber *rating1 = [(NSDictionary *)obj1 objectForKey:#"date"];
NSNumber *rating2 = [(NSDictionary *)obj2 objectForKey:#"date"];
return [rating1 compare:rating2];
}];
You can sort it easily by using sortArrayUsingComparator:
[array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return //pseudo-code: {obj1->dict->date isLaterThan obj2->dict->date};
}];
I sort it. Not sure that my code is clear and well optimized. But here is a solution:
NSMutableArray *masterArray = [NSMutableArray new];
NSMutableArray *sameDates = [NSMutableArray new];
BOOL started = NO;
NSString *prevDate;
for (NSDictionary *dict in sortedArrayWithFiles)
{
NSString *tempString = [dict objectForKey:#"date"];
if (started)
{
if ([tempString isEqualToString:prevDate])
{
[sameDates addObject:dict];
}
else
{
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:tempString forKey:tempString];
[tempDict setValue:sameDates forKey:#"files"];
[masterArray addObject:tempDict];
prevDate = tempString;
[sameDates removeAllObjects];
[sameDates addObject:tempString];
}
}
else
{
// first element
started = YES;
prevDate = tempString;
[sameDates addObject:dict];
}
}
// last value
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:prevDate forKey:prevDate];
[tempDict setValue:sameDates forKey:#"files"];
[masterArray addObject:tempDict];
In master array we store array with dictionaries separated by date.
I am having trouble reading the data in a plist file. I'm not getting the titleString printed in the console like I'm expecting. What am I doing wrong?
NSString *path = [[NSBundle mainBundle] pathForResource:#"Events" ofType:#"plist"];
NSDictionary *dictPri = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
NSMutableArray *arrEvents = [[NSMutableArray alloc] initWithArray:[dictPri valueForKey:#"Root"]];
for (NSDictionary *dict in arrEvents)
{
NSString *titleString = nil;
NSString *date = nil;
titleString = [NSString stringWithFormat:#"%#",[dict valueForKey:#"Title"]];
date = [NSString stringWithFormat:#"%#",[dict valueForKey:#"Date"]];
NSLog(#"Title String: %#", titleString);
}
Your main element (Root) is Dictionary - not Array - change it in plist by clicking on type next to it.
Also there is a problem in your code - you never access "Root" element by name - it's by default top-level object. Consider taking out additional array initialization which is not required.
Fixed code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Events" ofType:#"plist"];
NSArray* arrEvents = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *dict in arrEvents)
{
NSString *titleString = [NSString stringWithFormat:#"%#",[dict objectForKey:#"Title"]];
NSString *date = [NSString stringWithFormat:#"%#",[dict objectForKey:#"Date"]];
NSLog(#"Title String: %#", titleString);
}
I am trying to save an NSMutable Array and NSString into plist and then if it exists initialize the value from plist. However when I re run the app, the values do not get initialize as it is suppose to. So far the following is what I have.
if (self = [super init]) {
NSString *path=[self getFileUrl];
NSFileManager *fm = [[NSFileManager alloc] init];
if ([fm fileExistsAtPath:path]) {
_history = [d objectForKey:#"stringKey"];
class=[d objectForKey: #"ArrayKey"];
}
NSDictionary *d;
However the values are not getting initialized as per the plist. Is it the way I am extracting the values from the dictionary?
here is my function that saving json into plist in nscachesdirectory
-(void)saveproducts{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSDictionary*dict = [NSDictionary dictionary];
NSMutableArray *types = [NSMutableArray array];
NSArray *dictArray = [NSArray array];
NSArray *dictKeys = [NSArray array];
NSArray *productObjects = [NSArray array];
NSArray *productKeys = [NSArray array];
for (int i=0; i<appDelegate.products.count; i++) {
NSMutableArray *tmpProds = [NSMutableArray array];
NSString *t_ID = [[appDelegate.products objectAtIndex:i] valueForKey:#"id"];
NSString *t_image = [[appDelegate.products objectAtIndex:i] valueForKey:#"image"];
NSString *t_name =[[appDelegate.products objectAtIndex:i] valueForKey:#"name"];
NSArray *products = [[appDelegate.products objectAtIndex:i] valueForKey:#"products"];
NSDictionary *productsDict = [NSDictionary dictionary];
for (int j=0; j<products.count; j++) {
NSString *p_id = [[products objectAtIndex:j] valueForKey:#"id"];
NSString *p_name = [[products objectAtIndex:j] valueForKey:#"name"];
NSString *p_name2 = [[products objectAtIndex:j] valueForKey:#"name2"];
NSString *image = [[products objectAtIndex:j] valueForKey:#"image"];
NSString *typeID = [[products objectAtIndex:j] valueForKey:#"type_id"];
NSString *active = [[products objectAtIndex:j] valueForKey:#"active"];
NSString *available = [[products objectAtIndex:j] valueForKey:#"available"];
NSString *desc = [[products objectAtIndex:j] valueForKey:#"description"];
NSString *price = [[products objectAtIndex:j] valueForKey:#"price"];
if ([p_name2 isEqual:[NSNull null]]) {
p_name2 =#"undefined";
}
if ([desc isEqual:[NSNull null]]) {
desc = #"";
}
productObjects = [NSArray arrayWithObjects:p_id,p_name,p_name2,image,typeID,active,available,desc,price, nil];
productKeys = [NSArray arrayWithObjects:#"id",#"name",#"name2",#"image",#"type_id",#"active",#"available",#"desc",#"price", nil];
productsDict = [NSDictionary dictionaryWithObjects:productObjects forKeys:productKeys];
[tmpProds addObject:productsDict];
if (![image isEqualToString:#""]) {
[foodImages addObject:image];
}
}
dictArray = [NSArray arrayWithObjects:t_ID,t_image,t_name,tmpProds, nil];
dictKeys = [NSArray arrayWithObjects:#"id",#"image",#"name",#"products", nil];
dict = [NSDictionary dictionaryWithObjects:dictArray forKeys:dictKeys];
[types addObject:dict];
}
NSDictionary* plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:types, nil] forKeys:[NSArray arrayWithObjects:#"ptype", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:#"cached"];
[defaults synchronize];
}
else
{
NSLog(#"Error log: %#", error);
}
}
and this one reading plist
-(void)loadFromplist{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *dict = (NSDictionary*)[NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:nil errorDescription:nil];
productsArray = [dict valueForKey:#"ptype"];
[self.tableView reloadData];
}