NSString format not working on device but working on simulator - nsstring

just making a basic game and used the NSUserDefaults to save the high score. while calling the i needed to use a NSString with a Format of "Best Time : %i". I Ran the game on the simulator and it worked perfectly.
However when I went to run it on the device the label that i formatted using the NSString(format "Best Time : %i") did not work nothing appeared in the label?
Here is the code I used for calling the saved Best time:
//The previous games best time
var highscoreDefaults = NSUserDefaults.standardUserDefaults()
if (highscoreDefaults.valueForKey("Highscore") != nil){
theNewTime = highscoreDefaults.valueForKey("Highscore") as! NSInteger!
thehighscore.text = NSString(format: "Best Time : %i" , theNewTime) as String
}
//---------------------

You can use Swift's string interpolation as you don't need any advanced features from the C-format specifier:
thehighscore.text = "Best Time : \(theNewTime)"

Related

Changing the Session Languge leads to "java.text.ParseException: Unparseable date

whenever I'm defining the timeframe being in German session language after changing to English lang. session (and vice versa) I'm getting the:
java.text.ParseException: Unparseable date: "10.10.2018"
Here is the fragment:
Date startDateFormatted = DateUtils.convertDateToMinusDayNumber(cal, dayRange);
Date endDateFormatted = new Date();
if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate))
{
try
{
String datePattern = getLocalizedString("dd.MM.yyyy"); //
startDateFormatted = new SimpleDateFormat(datePattern).parse(startDate); // exception is throwing on this line
endDateFormatted = new SimpleDateFormat(datePattern).parse(endDate);
}
catch (final Exception e)
{
LOG.error(ERROR_DATE_PARSING, e);
}
}
java.time
I recommend you use java.time, the modern Java date and time API, for your date work.
String datePattern = "dd.MM.uuuu";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(datePattern);
String startDateString = "10.10.2018";
LocalDate startDate = LocalDate.parse(startDateString, dateFormatter);
System.out.println(startDate);
Output:
2018-10-10
If you want to support different date formats for different locales, let Java handle that part for you:
String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.MEDIUM, null, IsoChronology.INSTANCE, Locale.GERMAN);
German locale works with your example string of 10.10.2018. For UK locale, for example, a string like 10 Oct 2018 would be required instead, as Britons would typically expect.
What went wrong in your code?
We cannot tell from the information and code that you have provided exactly what happened. A couple of good guesses are:
As Arvind Kumar Avinash said in a comment, getLocalizedString() may be causing trouble. You may print datePattern to check. Localization is something you do to strings that you display to the user. Trying to localize a format pattern string for a formatter is probably plain wrong, so you should leave out that method call. That the error occurs when changing language seems to support this possibility.
There may be unexpected non-printing characters in your string. One way to check would be to print startDate.length(). If the length is greater than 10, there are more characters than the 10 chars in 10.10.2018.
Link
Oracle tutorial: Date Time explaining how to use java.time.

.Net Core 3 Preview SequenceReader Length Delimited Parsing

I'm trying to use SequenceReader<T> in .Net Core Preview 8 to parse Guacamole Protocol network traffic.
The traffic might look as follows:
5.error,14.some text here,1.0;
This is a single error instruction. There are 3 fields:
OpCode = error
Reason = some text here
Status = 0 (see Status Codes)
The fields are comma delimited (semi-colon terminated), but they also have the length prefixed on each field. I presume that's so that you could parse something like:
5.error,24.some, text, with, commas,1.0;
To produce Reason = some, text, with, commas.
Simple comma delimited parsing is simple enough to do (with or without SequenceReader). However, to utilise the length I've tried the following:
public static bool TryGetNextElement(this ref SerializationContext context, out ReadOnlySequence<byte> element)
{
element = default;
var start = context.Reader.Position;
if (!context.Reader.TryReadTo(out ReadOnlySequence<byte> lengthSlice, Utf8Bytes.Period, advancePastDelimiter: true))
return false;
if (!lengthSlice.TryGetInt(out var length))
return false;
context.Reader.Advance(length);
element = context.Reader.Sequence.Slice(start, context.Reader.Position);
return true;
}
Based on my understanding of the initial proposal, this should work, though also could be simplified I think because some of the methods in the proposal make life a bit easier than that which is available in .Net Core Preview 8.
However, the problem with this code is that the SequenceReader does not seem to Advance as I would expect. It's Position and Consumed properties remain unchanged when advancing, so the element I slice at the end is always an empty sequence.
What do I need to do in order to parse this protocol correctly?
I'm guessing that .Reader here is a property; this is important because SequenceReader<T> is a mutable struct, but every time you access .SomeProperty you are working with an isolated copy of the reader. It is fine to hide it behind a property, but you'd need to make sure you work with a local and then push back when complete, i.e.
var reader = context.Reader;
var start = reader.Position;
if (!reader.TryReadTo(out ReadOnlySequence<byte> lengthSlice,
Utf8Bytes.Period, advancePastDelimiter: true))
return false;
if (!lengthSlice.TryGetInt(out var length))
return false;
reader.Advance(length);
element = reader.Sequence.Slice(start, reader.Position);
context.Reader = reader; // update position
return true;
Note that a nice feature of this is that in the failure cases (return false), you won't have changed the state yet, because you've only been mutating your local standalone clone.
You could also consider a ref-return property for .Reader.

ASP -Set Current Date and time

When I run the ASP project in local host, show correct local time (Sri Lanka) . But when host the project show incorrect date, Time..
lable_date_time.Text = string.Format("{0}", DateTime.Today.ToShortDateString());
Hosting server in United states (www.smarterasp.net)
How to Fix it?
Thank You...
You might find the FindSystemTimeZoneById method useful, along with ConvertTimeFromUtc method. Both are methods of the System.TimeZoneInfo class. Example I used to pass the time in a time zone passed in from a user and converting that to stock market time in NYC. After you do the calculation you can adjust by getting the difference of the offset:
TimeZoneInfo tradeTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(tradeTimeZone);
var tradetz = TimeZoneInfo.ConvertTimeFromUtc(myexactexetime, tradeTimeZoneInfo);
TimeZoneInfo nyTZI = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var marketTimezone = TimeZoneInfo.ConvertTimeFromUtc(dateTimeInUsersZone, nyTZI);
TimeSpan diff = marketTimezone - tradetz;
double hours = diff.TotalHours;
dateTimeInUsersZone= dateTimeInUsersZone.AddHours(hours);

Core Data, problems when saving or retrieving, don't know where it is

I'm quite new with Core Data, and I'm having an issue that I don't understand. I don't know what's going wrong.
I'm saving into my Persistent Store, 7 objects of an entity "Weight" that is read from a JSON file with this code:
for (NSDictionary *values in aWeightValues)
{
weightValues = [NSEntityDescription insertNewObjectForEntityForName:#"Weight"
inManagedObjectContext:moc];
[weightValues setValue:[typeWeight objectForKey:#"unit"] forKey:#"unit"];
[weightValues setValue:[values objectForKey:#"timestamp"] forKey:#"date"];
[weightValues setValue:[values objectForKey:#"value"] forKey:#"amount"];
if (![moc save:&error])
{
NSLog(#"Problem saving: %#", [error localizedDescription]);
}
}
The for loop makes 7 loops, that means it's being saved correctly (speaking about the number of objects).
But then, when I try to retrieve data from the Persistent Store in this way:
-(NSMutableArray *) extractWeightEntities
{
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
NSError *error;
NSManagedObjectContext *moc = [appDelegate managedObjectContext];
NSEntityDescription *entityWeight = [NSEntityDescription entityForName:#"Weight" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc]init]autorelease];
[request setEntity:entityWeight];
entityWeight = nil;
fetchResult = [[moc executeFetchRequest:request error:&error]mutableCopy];
return (fetchResult);
}
and try to show one attribute of each object retrieved, I get 1044 rows in my TableView!! when I should have just 7.
What am I doing wrong? Is the problem when I'm saving, or when I'm retrieving?
I hope you can help to solve this issue. Many thanks in advance!!
You don't need to call save on each iteration of the loop, this is very inefficient. Save afterwards.
Put a breakpoint on you loop and ensure it is only going over it 7 times.
Is the data continuously accumulating? Are you deleting the app each time? If you keep running the code - it will keep adding objects to your datastore unless you check if they exist in the datastore before inserting them.

iPhone CoreData join

this is my core data model:
I'm trying to get all LanguageEntries from a database for a given category.categoryName and languageset.languageSetName e.g.
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"LanguageEntry" inManagedObjectContext:del.managedObjectContext];
[fetchRequest setEntity:entity];
NSString* predicateString = [NSString stringWithFormat:#"Category.categoryName = %# AND LanguageSet.languageSetName = %#",
#"Food", #"English####Spanish"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString];
NSError *error = nil;
NSArray* objects = [del.managedObjectContext executeFetchRequest:fetchRequest error:&error];
This always returns 0 objects. If I set the predicate string to match on one relationship (e.g. Category.categoryName = Food or languageSet.languageSetName = English####Spanish) it will return data.
This is baffling, can anyone shed some light?
->Ken
Your can't think of Core Data as SQL. There is no such thing as a "join" in Core Data. In this case, your trying to find the intersection of two sets of objects. Close to a join logically but not in the implementation details. And the programming devil is always in the details.
Try using the logical equal "==" like so:
#"Category.categoryName == %# AND LanguageSet.languageSetName == %#"
I believe that will solve your problem.
The data model has a predicate editor hidden way in it. It can help you set up predicates even if you don't embed them in fetches in model itself. Just select an entity, in your case "LanguageEntity", then add a Fetch Request. The edit predicate will appear and you can use the dialog to create the predicate. It will display a textual version of the predicate that you can copy into your code.
The predicate properly wasn't created correctly, you must pass the parameters to predicateWithFormat. It should have been:
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"Category.categoryName = %# AND LanguageSet.languageSetName = %#",
#"Food",
#"English####Spanish"];
In case you were wondering what that does is it puts quotes around the string parameters automatically which are required when using a string in a predicate. When you created the query using NSString's format method that did not put the required quotes in.

Resources