Comparing with NSMutableArray - iphone

In my Array 1, which I loaded images from NSDocumentDirectory, I loaded them and add a NSMutableDictionary:
self.images = [NSMutableArray array];
for(int i = 0; i <= 8; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
NSMutableDictionary *container = [[NSMutableDictionary alloc] init];
[container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:#"image"];
[container setObject:[NSNumber numberWithInt:i] forKey:#"index"];
[images addObject:container];
}
}
In my other array Array 2, I loaded them from the app.
self.images = [NSMutableArray arrayWithObjects:
#"01.jpg",#"02.jpg",#"03.jpg",#"04.jpg",#"05.jpg",#"06.jpg",#"07.jpg",nil];
I was able to add string to Array 2 like this:
for (int x=1; x<8;x++) {
// add as NSString
[images addObject:[NSString stringWithFormat:#"%d", x]];
}
And was able to compare Array 2 like this:
NSInteger index = carousel.currentItemIndex;
if ([[images objectAtIndex:index] intValue] == 1){
What I wanted to do, is to do it to Array 1.
I know Array 1 has been already added with NSNumber, but Im kinda new to NSMutableDictionary so I can't do it the same as Array 2.
Can it be done the same as my Array 2 or what is the other way?
Thanks for the help.

Actually Here you have the array of dictionaries, because you are adding the dictionary which has two objects with keys image and index
So, for retrieving the array of dictionaries,
just log it and see what happens
Edit 2.0
for(int i=0; i< [images count]; i++){
NSNumber *num =[[images objectAtIndex:i] objectForKey:#"index"];
int index = [num intValue];
NSLog(#"%d",index)
}

Related

How to separate parts of NSString?

I have a NSMutableArray of NSStrings where each element of array has the format equal to #"key is 1::value is 1". Now I want to store string part coming before "::" in an array1 and string part coming after "::" in an array2. How can I do that?
Here is the Code :
NSArray *temp = [YourString componentsSeparatedByString:#"::"];
NSString *str1 = [temp objectAtIndex:0];
NSString *str2 = [temp objectAtIndex:1];
But prior to accessing the Objects in the Array .. check for whether it contains the value.
Try this ::
NSString *s = #"key is 1::value is 1";
NSArray *a = [s componentsSeparatedByString:#"::"];
NSLog(#" -> %# --> %#", [a objectAtIndex:0], [a objectAtIndex:1]);
use this:
[array1 addObject:[[YourString componentsSeparatedByString:#"::"] objectAtIndex:0]];
[array2 addObject:[[YourString componentsSeparatedByString:#"::"] objectAtIndex:1]];
The key to splitting your strings is to use the componentsSeparatedByString: method on NSString to separate your string into an NSArray. Read the docs on how this method acts with blank strings etc, but it's what you'd use.
You said you have an array of strings, so the basic implementation would involve iterating over that array and adding each element to the two other arrays.
NSMutableArray *arrayOfStrings = [NSMutableArray array];
NSMutableArray *array1 = [NSMutableArray array];
NSMutableArray *array2 = [NSMutableArray array];
for (NSString *string in arrayOfStrings)
{
NSArray *components = [string componentsSeparatedByString:#"::"];
if ([components count] == 2)
{
NSString *obj1 = [components objectAtIndex:0];
NSString *obj2 = [components objectAtIndex:1];
[array1 addObject:obj1];
[array2 addObject:obj2];
}
}
I found the way. I will keep adding the beforeString and afterString in array1 and array 2 respectively while iterating the elements of original array
for(int i=0;i<self.originalArray.count;i++)
{
NSString *temp=[self.originalArray objectAtIndex:i];
NSRange r = [temp rangeOfString:#"::"];
NSString *beforeString = [temp substringToIndex:r.location];
NSString *afterString = [temp substringFromIndex:r.location+2];
[array1 addObject:beforeString];
[array2 addObject:afterString];
}

How to sort plist by its value

I have Plist with list with List of Dictionaries(item0,item1,item2).and I populate this plist in the Graph..its works fine.and in Plist key (date)-> Value(i store by using NSDate) .Now I need to sort the Plist in such a way that:-
graph should display for only one week.
say if first value is 26-Dec-12 than only upto 1-Jan-13(1 week) values plist should display
.
code :
- (NSArray *)readFromPlist
{
// get paths from root direcory
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"calori.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
valueArray = [dict objectForKey:#"title"];
return valueArray;
}
and
- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef _context = UIGraphicsGetCurrentContext();
ECGraph *graph = [[ECGraph alloc] initWithFrame:CGRectMake(10,10, 480, 320)
withContext:_context isPortrait:NO];
NSMutableArray *Array=[NSMutableArray arrayWithArray:[self readFromPlist]];
NSMutableArray *items = [[NSMutableArray alloc] init];
for (id object in [Array reverseObjectEnumerator]){
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
tempItemi =[[ECGraphItem alloc]init];
NSString *str=[objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
NSString*str1=[objDict objectForKey:#"date"];
NSLog(#" str values2-- %#",str1);
tempItemi.isPercentage=YES;
tempItemi.yValue=f;
tempItemi.name=str1;
[items addObject: tempItemi];
}
}
[graph drawHistogramWithItems:items lineWidth:2 color:[UIColor blackColor]];
}
As your requirement is to filter date within 7 days,
I am giving you a logic, try this way:
- (NSArray *)readFromPlistForOneWeek {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"calori.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
//loop through each of the item
//and check if <8 then add that keyValue to array
NSMutableArray *tempValueArray=[NSMutableArray new];
for (NSDictionary *subDict in [dict objectForKey:#"title"]) {
// NSLog(#"=> %#",subDict);
NSString *plistDateString=[subDict objectForKey:#"date"];
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"dd-MMM-yy"];
NSDate *plistDate=[dateFormatter dateFromString:plistDateString];
NSString *currentDateString=[dateFormatter stringFromDate:currentDate];
NSTimeInterval secondsBetween = [plistDate timeIntervalSinceDate:currentDate];
NSInteger dateDiff = secondsBetween / 86400;
if( dateDiff<8 ){ //within 0-7 days
[tempValueArray addObject:subDict];
}
}
NSLog(#"valuArray : %#",tempValueArray);
return tempValueArray;
}
Have you tried with NSSortDescriptor?
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:#"DATE" ascending:YES selector:#selector(compare:)];
[yourDictionary sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
Try this
NSString *path = [[NSBundle mainBundle] pathForResource:#"yourfile" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
// sort it
NSArray *sortedArray = [[myDict allKeys] sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
// iterate and print results
for(NSString *key in sortedArray) {
NSLog(#"key=%#,value=%#", key, [dict objectForKey:key]);
}

Credential editing in Plist if Correct

In plist I have stored Credentials from that I need to check for the correct Credential and if the correct Credential match then replace the password field with the new..for this I Have 3 UITextField . A for new email-id ,b for current password and c for new password ..if a==b means current password == email id then new password entered in the c textfield should replace in the current password field in plist
.
- (void)authenticateCredentials {
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:#"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:#"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
// what should be the condition to replace current password to new password
}
NSLog(#"INCorrect credentials");
} else {
NSLog(#"Error! Not a dictionary");
}
}
}
Check if this will work for you.
- (void)authenticateCredentials {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"XYZ.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
NSArray *plistArray = [dict objectForKey:#"title"];
NSMutableArray *plistUpdatedArray = [NSMutableArray arrayWithArray:plistArray];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:#"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:#"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithDictionary:objDict];
[dict1 setObject:newPassword forKey:#"title"];
[plistUpdatedArray replaceObjectAtIndex:i withObject:dict1];
NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithDictionary:dict];
[dict2 setObject:plistUpdatedArray forKey:#"title"];
[dict2 writeToFile:documentPlistPath atomically:YES];
return;
}
NSLog(#"INCorrect credentials");
} else {
NSLog(#"Error! Not a dictionary");
}
}
}
If your plist is in bundle you can't change the value stored in it.
So copy it to document directory before doing any change.
Answer to your question:
if([emailField.text isEqualToString:currntPwd.txt])
{
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
[newDict addEntriesFromDictionary:objDict];
[newDict setObject:#"Midhun" forKey:#"pass"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
NSString *plistPath = [docDirectory stringByAppendingPathComponent:#"yourPlist.plist"];
[[NSFileManager defaultManager] removeItemAtPath:plistPath];
[newDict writeToFile:plistPath atomically:YES];
}

How to fetch data from pList in Label

I have a RegistrationController screen to store email-id ,password,DOB,Height,Weight and logininController screen to match email-id and password to log-in purpose.
Now, In some third screen I have to fetch only the Height,Weight from the plist of the logged-in user to display it on the label.now if I Store the values of email-id and password in from LoginViewController in string and call it in the new screen to match if matches then gives Height,Weight ..if it corrects then how to fetch Height,Weight from the plist of the same one.
How can I fetch from the stored plist in a string?
Here is my code:
-(NSArray*)readFromPlist
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"XYZ.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
NSArray *valueArray = [dict objectForKey:#"title"];
return valueArray;
}
- (void)authenticateCredentials {
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:#"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:#"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
return;
}
NSLog(#"INCorrect credentials");
} else {
NSLog(#"Error! Not a dictionary");
}
}
}
First get whole value from your plist file after that store this NSArray into NSMutableArray and get the value with its objectAtIndex and valueForKey property..see whole example bellow..
UPDATE :
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"yourFileName" ofType:#"plist"];
NSArray *contentArray = [NSArray arrayWithContentsOfFile:plistPath];
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithArray:contentArray];
for (int i = 0; i< [yourArray count]; i++)
{
id object = [yourArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
yourLableWeight.text = [[objDict objectForKey:#"Weight"];// set index with your requirement
yourLableHeight.text = [[objDict objectForKey:#"Height"];
}
hope this help you...
When you enter credentials on login screen to check when it match the credentials with the fetched plist then pass that plist to the next controller. Do something like this
UserViewController *controller = [[UserViewController alloc] initWithNibName:#"UserViewController" bundel:nil];
[controller setUserDictionary:yourPlistDictionary];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
in UserViewController you would have a NSDictionary instance to store the data to show, hope that will help you

Searching for objects in array by name

is there a possibility to check for an object in an array by name.
At some point in my app I need to access the plist and pull information stored under an object which I found by its name.
The reason I need to do this is because I don't have the integer number under which where the object is placed in my array.
I have started the usual procedure but i'm not getting anywhere. Maybe its just getting a little too late for me....
This is how my plist looks
Array
Dictionary
title ...
text ...
ect ...
Dictionary
title ...
text ...
ect ...
Dictionary
title ...
text ...
ect ...
My code so far isn't helping at all. I'm definitely doing something wrong.
-(NSString*)nameFromPlist:(NSString*)name {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"Orte.plist"];
_regionArray = [NSArray arrayWithContentsOfFile:writableDBPath];
NSString *string = [[NSString alloc]init];
for(NSDictionary *dict in _regionArray) {
string = [[dict objectForKey:name] valueForKey:#"title"];
}
return [NSString stringWithFormat:#"%#",string];
}
My string is just returning null.
Any ideas anyone?
Thanks a lot!
ANSWER:
Here is the code for everyone:
-(NSString*)nameFromPlist:(NSString*)name {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tmpFileName = [[NSString alloc] initWithFormat:#"Orte.plist"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:tmpFileName];
NSString *string;
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
NSDictionary *dict = [[NSDictionary alloc] init];
NSString *title;
for (int i=0; i<[array count]; i++) {
dict = [array objectAtIndex:i];
title = [dict valueForKey:#"title"];
if([title isEqualToString:name]) {
string = [dict valueForKey:#"title"];
NSLog(#"Titel: %#", string);
}
}
return [NSString stringWithFormat:#"%#",string];
}
Thank a lot everyone!
First you don't need to alloc the NSString, 'cause you'll get a different one from valueForKey.
Then if I understood right what you want to get a better code may be something that make use of NSPredicate or the block-based indexOfObjectPassingTest. Both iterate across the array and perform a test on the elements to get you the matching elements (or the index of them).
NSString* plistPath = [[NSBundle bundleForClass:[self class]] pathForResource:#"<PlistFileName>" ofType:#"plist"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
NSMutableArray* titles = [[NSMutableArray alloc] init];
for (NSDictionary* d in array)
[titles addObject:[d objectForKey:#"title"]];
NSLog(#"Object found at index %i", [a indexOfObject:#"<Your object name>"]);
Make sure you're testing against NSNotFound for failure to locate, and not (say) 0.