Error: Value of type 'String' has no member 'totalAnswered' - ios

I am using CoreData for my project and I came into this error:
Error: Value of type 'String' has no member 'totalAnswered'
Here is my circumstance:
I have a CoreData model with the entity "Scores" and the ff. attributes:
datePlayed
totalScore
totalAnswered
I am using a table to show the data above.
Here is the problem part of my code for the Cell data:
if let date = score.datePlayed, let score = score.totalScore, let questions = score.totalAnswered {
I have no trouble saving into the entity "Scores" using the term "score" as illustrated in the code above. Also, I have no trouble showing the "score.datePlayed" and the "score.totalScore". However, the code "score.totalAnswered" is where I am having problems. It receives the error code above.
I have tried cleaning my project but the error still persist.
What should I do to show the data of "score.totalAnswered"?
EDIT:
I am using the code above to display the data using the ff. code:
cell.textLabel?.text = "Date: \(date)\nScore: \(score)/\(questions)"

Look at the 2nd let. You create a new variable named score that hides the original variable named score. So the 3rd let is trying to access the wrong score.
The best solution is to use a different variable name on the 2nd let.

Related

Delete members of list when deleting list in Core Data / iOS / Swift 5

I have two entities: Item (which keeps track of lists) and Tasks (which are task items within lists). In one view of the app, there is a swipe to delete feature which removes the list. This works with the following code:
offsets.map { items[$0] }.forEach(viewContext.delete)
I would like to delete now obsolete tasks for the list being deleted. I first tried this code:
tasks.filter{$0.listID! == listsID}.forEach(viewContext.delete)
I was proud of myself. What an elegant solution. Swift hated it. I get an error that says
Reference to member 'listID' cannot be resolved without a contextual type
I Googled and SOd and got nowhere. I don't know what that error means and can't figure out how to fix it in XCode 12 / iOS 14. So then I came up with the following not so elegant code:
let listsID = offsets.map {items[$0].id!}
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Tasks.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "listID == %#", listsID)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
deleteRequest.resultType = .resultTypeObjectIDs
do {
let result = try viewContext.execute(deleteRequest)
guard
let deleteResult = result as? NSBatchDeleteResult,
let ids = deleteResult.result as? [NSManagedObjectID]
else {return}
let changes = [NSDeletedObjectsKey: ids]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes,
into: [viewContext])
}
catch {
print(error as Any)
}
listsID captures the UUID of the list and stores it as a variable. However, you'll note that it is stored as an ARRAY (ugh). The fetchRequest.predicate code filters the tasks so that only those that have the attribute of 'listID' (which helps connect the task to the list it belongs to) matching the id of the list being deleted is pulled.
The code compiles (yay!). Then I get the following error when trying to delete a list:
Exception NSException * "Unexpected or improperly formatted UUID parameter with type Swift.__SwiftDeferredNSArray, expected NSUUID or well-formed NSString" 0x0000600003145b30
I'm sure there is a simple way to do this. I played with inverse relationships in Core Data but got nowhere. I didn't know how to tell it that 'id' (UUID) in 'Item' == 'listID' (UUID) in 'Tasks', so deleting the list didn't do anything to the tasks that belong to it.
I tried to create a ForEach loop, but ran into various errors that I couldn't resolve. I'd prefer to use the elegant code that I wrote at the top to make the deletion happen. Any ideas?
Thank you.
The credit for this goes to pbasdf for his super helpful responses. I used this link to learn about setting up relationships in Core Data: Seneca SDDS. I was missing one line in my persistence model:
newTask.list = newItem
How I solved this problem (in case it helps someone else) is that I created a one to many relationship for Item (the list of lists), and one to one relationship for Tasks (tasks are a subset of a list). Now, when I create a new task in the persistence script, I have a pointer back to the list it belongs to - hence the single line of code above.
The additional background that helped me understand Core Data relationships can be found in the link above. This snippet in particular was very helpful (in case the page goes 404):
Adding a new object, and setting the relationship
Assume that you have a reference to a Company object already; its variable name is c. How do you add a new Employee or Product? Create the new object and set its relationship. The relationship can be configured from either direction. In this section, we will configure it from the perspective of the just-added new object. For example:
// As noted above, assume that you have a reference
// "c" to an existing Company object...
// Create and configure a new employee
let peter = Employee(context: m.ds_context)
peter.name = "Peter McIntyre"
peter.age = 23
// etc.
// Now, set the relationship
peter.company = c
m.ds_save()
That’s it. If it seems too easy, well, it is easy.

Assigning Value to StringValue In F#

I am working though this example of the Open XML SDK using F#
When I get to this line of code
sheet.Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart)
I am getting a null ref exception when I implement it like this:
sheet.Id.Value <- document.WorkbookPart.GetIdOfPart(worksheetPart)
Is there another way to assign that value? System.Reflection?
I got it working like this:
let sheet = new Sheet
(
Id = new StringValue(spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart)),
SheetId = UInt32Value.FromUInt32(1u),
Name = new StringValue("mySheet")
)
If You want to take a look to the entire sample translated to F#, it's here.
To clarify what's going on, the problem is that sheet.Id is initially null. If we look at the following:
sheet.Id.Value <- document.WorkbookPart.GetIdOfPart(worksheetPart)
The code tries to access the sheet.Id and invoke its Value property setter, but the Id itself is null. The answer posted by Grzegorz sets the value of the whole Id property - it's done in a construtor syntax, but it's equivalent to writing the following:
sheet.Id <- new StringValue(spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart))
This sets the whole Id property to a new StringValue instance.

Extraneous argument label 'localeID' in call (SwiftDate)

I am developing an iOs application with Swift and a total novice in application development. I use SwiftDate external library to deal with dates. SwiftDate is installed with CocoaPods and it is imported correctly in the project.
But I can't figure out why I get this error when I compile my project :
Extraneous argument label 'localeID' in call
For this code :
let now = NSDate()
let nowHere = now.toString() // E.g. 21-Dec-15 12:00 CET
let nowInFrench = now.inRegion(localeID: "fr_FR").toString()
I understand that's because the parameters are not formatted correctly, but this an exemple from the documentation so I am a little bit lost for this problem.
Thank's.
As Oliver mentioned, the first problem is the argument label in
let nowInFrench = now.inRegion(localeID: "fr_FR").toString()
to fix your
Extraneous argument label 'localeID' in call
error write it like this
let nowInFrench = now.inRegion("fr_FR").toString()
then you will come to the
Cannot convert value of type string to expect argument type Region
Error. This means you cannot simply give the function inRegion a String object. It wants a Region objects. The documentation says use create a region
let paris = DateRegion(timeZoneID: "CEST", localeID: "fr_FR")
let nowInFrench = now.inRegion(paris).toString()
The error is being flagged up because for the first argument in a function the label doesn't need to be written, only the ones after that.
If you just write:
let nowInFrench = now.inRegion("fr_FR").toString()
The error should go away.
I don't know why the example is written that way, maybe just for clarity.
Edit: having looked at the documentation I do think they have just included the labels to be clear as to what type they are using as an argument.

'AnyObject' Doesn't have a Member "contactUID" Even thought Intelitype Says it Does?

Another ameture hour Swift Programming Question.
I have been returning values for an object from an array of object "Any Object" "Results". The intellitype says I have an object in the array with a value "ContactUID" however when I try to use ContactUID I get an error saying 'AnyObject' Doesn't contain member 'contactUID'.
The Array called HBCContactList successfully returns, FirstName, LastName and all the other items listed on the screen in the code. However it Will not return the Value 'ContactUID'.
The Model has got the right item. However unlike all the others... ContactUID is a INT64 instead of a string... I have added some screenshots to assit with the process of explaining. Sorry it sounds complicated but I expect I am missing something stupid.
Autocomplete on iOS isn't always accurate, often it will just list all possible selectors / methods.
The root of your problem here is that even though you know HCCContactList holds only HBCDirectoryModel objects, the compiler doesn't as MOContext.executeFetchRequest(freq, error: nil) returns an Array which declares it contains AnyObject's ([AnyObject] / Array<AnyObject>). In order to refer to any of these objects as an HBCDirectoryModel you'll need to conduct a cast to this type.
The easiest way to do this is is to declare your HCCContactList as being an array of HBCDirectoryModel's instead of AnyObject's, and then casting the result of calling MOContext.executeFetchRequest() to this same type.
You can do this as follows
var HCCContactList: Array<HBCDirectoryModel> = []
HCCContactList = MOContext.executeFetchRequest(freq, error: nil) as Array<HBCDirectoryModel>
Or using the shorter syntax
var HCCContactList:[HBCDirectoryModel] = []
HCCContactList = MOContext.executeFetchRequest(freq, error: nil) as [HBCDirectoryModel]

How to use Slickgrid Formatters with MVC

I am working on a first Slickgrid MVC application where the column definition and format is to be stored in a database. I can retrieve the list of columns quite happily and populate them until I ran into the issue with formatting of dates. No problem - for each date (or time) column I can store a formatter name in the database so this can be retrieved as well. I'm using the following code which works ok:
CLOP_ViewColumnsDataContext columnDB = new CLOP_ViewColumnsDataContext();
var results = from u in columnDB.CLOP_VIEW_COLUMNs
select u;
List<dynColumns> newColumns = new List<dynColumns>();
foreach(CLOP_VIEW_COLUMN column in results)
{
newColumns.Add(new dynColumns
{
id = column.COLUMN_NUMBER.ToString(),
name = column.HEADING.Trim(),
field = column.VIEW_FIELD.Trim(),
width = column.WIDTH,
formatter = column.FORMATTER.Trim()
});
}
var gridColumns = new JavaScriptSerializer().Serialize(newColumns);
This is all fine apart from the fomatter. An example of the variable gridColumns is:
[{"id":"1","name":"Date","field":"SCHEDULED_DATE","width":100,"formatter":"Slick.Formatters.Date"},{"id":"2","name":"Carrier","field":"CARRIER","width":50,"formatter":null}]
Which doesn't look too bad however the application the fails with the error Microsoft JScript runtime error: Function expected in the slick.grid.js script
Any help much appreciated - even if there is a better way of doing this!
You are assigning a string to the formatter property, wich is expected to be function.
Try:
window["Slick"]["Formatters"]["Date"];
But i really think you should reconsider doing it this way and instead store your values in the db and define your columns through code.
It will be easier to maintain and is less error prone.
What if you decide to use custom editors and formatters, which you later rename?
Then your code will break or you'll have to rename all entries in the db as well as in code.

Resources