NSString to NSDate conversion..is there a better way? - nsstring

I need to convert a NSString object of format "Tuesday 14th October" to NSDate, of format "Tuesday, 14 Oct". This is what I tried,
NSString *day = #"Tuesday 14th October";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:#"EEEE, dd MMM"];
NSArray *dateComponets = [day componentsSeparatedByString:#" "];
NSString *dayOfTheWeek = dateComponets[0];
NSString *date = [dateComponets[1] substringToIndex:2];
NSString *month = [dateComponets[2] substringToIndex:3];
NSString *newDay = [NSString stringWithFormat:#"%#, %# %#", dayOfTheWeek,date, month];
NSDate *newDate = [dateFormatter dateFromString:newDay];
NSLog(#"date : %#", [dateFormatter stringFromDate:newDate]);
It seems to work but I felt its a bit clunky..do you guys know more elegant/better/standard way to do this in iOS?

Store an NSDate in Core Data - So:
NSString *day = #"Tuesday 14th October";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE dd MMM"];
myCoreDataObject.savedDate = [dateformatter dateFromString: day];
Then do the reverse when you want to display it:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE, dd MMM"];
myLabel.text = [dateformatter stringFromDate: myCoreDataObject.savedDate];
Don't actually allocate a new data formatter each time, its really slow.
The locale will default to the system one, so you don't need to explicitly set it necessarily

There is no such thing as an "NSDate of firmat X"; you've fundamentally failed to understand NSDate. It's a timestamp. It identifies an objective instant in time. It has no format.
Just use NSDateFormatter for whatever it is you actually want to do. It can parse a string into a date and vice versa. Don't write your own hacky text parsing. Don't touch NSDateComponents at all.

Related

Unable to append items in value array of mutable dictionary

NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary: #{ #"Maruti":#[#"m1",#"m2"], #"Hyundai":#[#"h1",#"h2"] } ];
How can I add values in value array of each key so that my output would look like:
Maruti:[m1,m2,m3] Hyundai:[h1,h2,h3]
Both Maruti and hyundai dictionary are NSDictionary so you cannot add any new values into them , plus you cannot use any of them outside of the scope of this method, but if you still want to do something like this you can go with this.
NSMutableDictionary * tempDict = [[NSMutableDictionary alloc]init];
[tempDict setValue:#"5" forKey:#"number"];
[tempDict setValue:#"6" forKey:#"Hidden"];
NSMutableDictionary *tempDict2 = [[NSMutableDictionary alloc]init];
[tempDict setValue:#"5" forKey:#"number"];
[tempDict setValue:#"6" forKey:#"Hidden"];
NSMutableDictionary *mutableDict=[[NSMutableDictionary alloc] init];
[mutableDict setValue:tempDict forKey:#"Dict 1"];
[mutableDict setValue:tempDict2 forKey:#"Dict 2"];

NSString with HTML code to NSData

Thanks in advance!
I'm wondering if it's possible to convert HTML code stored in a NSString to a NSData to parse later.
I'm reading from a BBDD the HTML code and saving it into a NSString.
NSString *htmlString =#"<html><body><p>introduccion</p><p>introducción</p></body></html>";
I want to use:
NSData *nsData = [[NSData alloc] initWithContentsOfURL:url];
But instead of initWithContentsOfURL i have to use the htmlString because I have the code stored in a BBDD and I am accessing it and storing the code to a NSString
Thanks!
Why dont you use standard methods to convert NSString to NSData like this:
NSData* data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
I have some html formatted text in my "subject.details", I add some more html formatting on the front and back. Giving me a "detailsStringForDisplay" NSString.
I convert this string to an NSData.
Set up a dictionary, which only contains one element to say that the document type is HTML.
Then finally set an attributedText using the data and the dictionary.
NSString *fontDetailsHTML = #"<div style=\"font-size:17px; text-family:Georgia; \">";
NSString *detailsString = subject.details;
NSString *endFontDetailsHTML = #"</div>";
NSString *detailsStringForDisplay = [NSString stringWithFormat:#"%#%#%#",fontDetailsHTML,detailsString,endFontDetailsHTML];
NSData *labelTextData = [detailsStringForDisplay dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:true];
NSDictionary *attributesForText = [[NSDictionary alloc]initWithObjectsAndKeys:NSHTMLTextDocumentType,NSDocumentTypeDocumentAttribute , nil];
self.detailDescriptionLabel.attributedText = [[NSAttributedString alloc]initWithData:labelTextData options:attributesForText documentAttributes:nil error:nil];

Declaring an NSDictionary with an NSString as its name

Ok, so I would like to create an NSDictionary, but the pointer should be followed by the value of an NSString that has been put in by the user. Is this possible? I imagine it would be something along the lines of this...
someNSString = _someTextField.text;
NSDictionary * {someNSString} = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:someUnimportantVariable], #"someUnimportantKey",...nil]
Thanks in advance, I realize that this is either completely not possible or there is a pretty simple solution. Either way, I'm sorry if I wasted your time.
you could try creating a "dictionary of dictionaries". something to the effect of:
someNSString = _someTextField.text;
NSDictionary *myDictionary = [[NSDictionary alloc] init];
[myDictionary setObject:[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:someUnimportantVariable], #"someUnimportantKey",...nil] forKey:someNSString];
and if you wanted to get back that dictionary
NSDictionary someNSStringDictionary = [myDictionary objectForKey:someNSString];
let me know if it helps in any way.

How to limit NSNumberFormatterCurrencyStyle

I have this in my code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *currency = [defaults objectForKey:#"currencySymbol"];
NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:#"." withString:#""];
text = [text stringByReplacingOccurrencesOfString:currencySymbol withString:#""];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
[numberFormatter setCurrencySymbol:currency];
NSNumber *number = [NSNumber numberWithDouble:[text intValue]*0.01];
text = [numberFormatter stringFromNumber:number];
textField.text = text;
and it works great until you reach a certain amount, then it can't go higher, for example:
2,500.00 (is possible)
25,000.00 (it´s not possible)
Maybe it´s something stupid, could anyone alert me what is that i am not seeing?
Thanks.
For those who are having the same problem, we have to add this line of code:
text = [text stringByReplacingOccurrencesOfString:#"," withString:#""];
Because (logically) the , is used for thousands...

CoreData - NSPredicate formated with time range (NSTimeInterval)

I'm trying to find out how to go through my CoreData information and find objects that have a createdAt (part of my object as an NSDate) that is within a NSTimeInterval. How do I set this up?
I've looked on the documentation at:
http://developer.apple.com/documentation/Cocoa/Conceptual/Predicates/predicates.html
But I'm not finding anything there.
Do I need to create two time stamps and use SQL's BETWEEN?
Any help would be wonderful.
First of all, it doesn't make sense to check if an NSDate is within an NSTimeInterval, because NSTimeInterval just specifies a length of time, not its location. Instead, you want to use two separate NSDates specifying the beginning and end of your intervals.
Here's what it would look like (beginningTime and endTime are NSDates).
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:#"YourEntityName" inManagedObjectContext:yourContext];
NSPredicate *beginningPredicate = [NSPredicate predicateWithFormat:#"createdAt >= %#", beginningTime];
NSPredicate *endPredicate = [NSPredicate predicateWithFormat:#"createdAt <= %#", endTime];
request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:beginningPredicate, endPredicate, nil]];
NSArray *results = [yourContext executeFetchRequest:request error:NULL];

Resources