I've been teaching myself programming from scratch by creating a simple app in Objective C. Today, I was faced with the issue that I had to write a method that didn't know what type of object it was going to get. With the help of Google, I was delighted to discover something called "casting". :)
I am using casting like so:
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
((SpecialViewController *)viewController).aProperty = somethingInteresting;
((SpecialViewController *)viewController).anotherProperty = somethingElse;
((SpecialViewController *)viewController).yetAnotherProperty = moreStuff;
}
Do I have to cast on every line like that, or is there a way I can cast "viewController" once in the scope of the method, to make my code neater?
You can cast your controller to temp variable and use it (also added type check - just in case) :
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
if ([viewController isKindOfClass:[SpecialViewController class]]){
SpecialViewController *special = (SpecialViewController *)viewController;
special.aProperty = somethingInteresting;
special.anotherProperty = somethingElse;
special.yetAnotherProperty = moreStuff;
}
}
How about:
- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController
{
SpecialViewController * controller = (SpecialViewController *)viewController;
controller.aProperty = somethingInteresting;
controller.anotherProperty = somethingElse;
controller.yetAnotherProperty = moreStuff;
}
Use one variable like
SpecialViewController *tempController = (SpecialViewController *)viewController;
than use this variable to access value like
tempController.aProperty
Related
I try to implement a search with entity when a search field is provided
but I get a weird casting error I just dont understand
Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[SomeApp.Models.Partner]' to type 'Microsoft.EntityFrameworkCore.DbSet`1[SomeApp.Models.Partner]'.
here is the code of my controller entry point
I tried forcing the cast, but apparently there is something wrong with my code
[HttpPost]
public async Task<ActionResult<PartnersFetch>> GetPartners(PartnersSearch partnersSearch)
{
DbSet<Partner> data = _context.Partners;
if (partnersSearch.SearchById != null)
{
// the following line causes problems :
data = (DbSet <Partner>) data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}
thanks for helping me on this
I forgot to use AsQueryable
var data = _context.Partners.AsQueryable();
if (partnersSearch.SearchById != null)
{
data = data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}
data.Where(...) will return an IQueryable which you can materialize as follows
List<Partner> myResult = data.Where(...).ToList();
The DbSet<Partner> is only the set on which you can query data. Your goal very likely is to get the partners out of it, right?
I post a request to get some json data and try to convert the data to Model
var newDrugs = Array<DxyDrugInfo>()
newDrugs = self.parseDrugJsonToModels(data) ?? []
private func parseDrugJsonToModels(data: NSData) -> Array<DxyDrugInfo>?{
let json = JSON(data: data)
if let drugsArray = json["data"].arrayObject as? Array<[String : AnyObject]>, success = json["success"].bool where success {
var sortedArray = Array<DxyDrugInfo>()
for drugDic in drugsArray {
let drugInfo = DxyDrugInfo()
drugInfo.setValuesForKeysWithDictionary(drugDic)
sortedArray.append(drugInfo)
}
return sortedArray
}
return nil
}
DxyDrugInfo is a Objective-C Model Class
My question is the sortedArray's type is Array of DxyDrugInfo, and it changed to
when assigned to newDrugs.
I want to convert it to DxyDrugInfo and I also want to what the type is.
Thank you
That type you're looking at, #lvalue [DxyDrugInfo], is "array of DxyDrugInfo". You're already done! The square brackets around a type are shorthand for "array", that is:
[DxyDrugInfo] == Array<DxyDrugInfo>
and #lvalue just means that newDrugs is a variable you can assign to. (It's the opposite of "r-value", which is a value you could assign to an "l-value".)
I am modifying the SalesConfirmDP class and trying to add the CustVendExternalItem.ExternalItemTxt field into a new field I have created.
I have tried a couple of things but I do not think my syntax was correct i.e I declare the CustVendExternalItem table in the class declaration. But then when I try to insert CustVendExternalItem.ExternalItemTxt into my new field, it does not populate, I guess there must be a method which I need to include?
If anyone has any suggestion it would be highly appreciated.
Thank you in advance.
private void setSalesConfirmDetailsTmp(NoYes _confirmTransOrTaxTrans)
{
DocuRefSearch docuRefSearch;
// Body
salesConfirmTmp.JournalRecId = custConfirmJour.RecId;
if(_confirmTransOrTaxTrans == NoYes::Yes)
{
if (printLineHeader)
{
salesConfirmTmp.LineHeader = custConfirmTrans.LineHeader;
}
else
{
salesConfirmTmp.LineHeader = '';
}
salesConfirmTmp.ItemId = this.itemId();
salesConfirmTmp.Name = custConfirmTrans.Name;
salesConfirmTmp.Qty = custConfirmTrans.Qty;
salesConfirmTmp.SalesUnitTxt = custConfirmTrans.salesUnitTxt();
salesConfirmTmp.SalesPrice = custConfirmTrans.SalesPrice;
salesConfirmTmp.DlvDate = custConfirmTrans.DlvDate;
salesConfirmTmp.DiscPercent = custConfirmTrans.DiscPercent;
salesConfirmTmp.DiscAmount = custConfirmTrans.DiscAmount;
salesConfirmTmp.LineAmount = custConfirmTrans.LineAmount;
salesConfirmTmp.CurrencyCode = custConfirmJour.CurrencyCode;
salesConfirmTmp.PrintCode = custConfirmTrans.TaxWriteCode;
if (pdsCWEnabled)
{
salesConfirmTmp.PdsCWUnitId = custConfirmTrans.pdsCWUnitId();
salesConfirmTmp.PdsCWQty = custConfirmTrans.PdsCWQty;
}
**salesConfirmTmp.ExternalItemText = CustVendExternalItem.ExternalItemTxt;**
if ((custFormletterDocument.DocuOnConfirm == DocuOnFormular::Line)
|| (custFormletterDocument.DocuOnConfirm == DocuOnFormular::All))
{
docuRefSearch = DocuRefSearch::newTypeIdAndRestriction(custConfirmTrans,
custFormletterDocument.DocuTypeConfirm,
DocuRestriction::External);
salesConfirmTmp.Notes = Docu::concatDocuRefNotes(docuRefSearch);
}
salesConfirmTmp.InventDimPrint = this.printDimHistory();
Well, AX cannot guess which record you need, there is a helper class CustVendExternalItemDescription to deal with it:
boolean found;
str externalItemId;
...
[found, externalItemId, salesConfirmTmp.ExternalItemText] = CustVendExternalItemDescription::findExternalItemDescription(
ModuleCustVend::Cust,
custConfirmTrans.ItemId,
custConfirmTrans.inventDim(),
custConfirmJour.OrderAccount,
CustTable::find(custConfirmJour.OrderAccount).CustItemGroupId);
The findExternalItemDescription method returns more information than you need here, but you have to define variables to store it anyway.
Well, the steps to solve this problem are fairly easy and i will try to give you a step by step approach how to solve this problem.
1) Are you initialising CustVendExternalItem properly? Make a record of the same and initialise it as Jan has shown above, then debug your code and see if the value is being initialised in your DP class.
2)If your value is being initialised correctly, but it is not showing up in the report design there can be multiple issues such as:
Overlapping of text boxes.
Insufficient space for the given field
Some report parameter/property not being set correctly which causes
your value not to show up on the report.
Check these one by one and you should end up arriving towards a solution
I am badly stuck trying to get my userInfo reference. One of my method is returning instance of the object. Everytime createUserInfo is called, it will return the userInfoObject to the lua.
However, when I call a method for userInfo object from Lua, I am not able to get the reference of the userInfo object (lua_touserdata(L,1))
static int getUserName (lua_State *L){
UserInfo **userInfo = (UserInfo**)lua_touserdata(L,1);
// The following is throwing null! Need help.
// Not able to access the userInfo object.
NSLog(#"UserInfo Object: %#", *userInfo);
}
static const luaL_reg userInstance_methods[] = {
{"getUserName", getUserName},
{NULL, NULL}
}
int createUserInfo(lua_State *L){
UserInfo *userInfo = [[UserInfo alloc] init];
UserInfoData **userInfoData = (UserInfoData **)lua_newuserdata(L, sizeof(userInfo*));
*userInfoData = userInfo;
luaL_openlib(L, "userInstance", userInstance_methods, 0);
luaL_getmetatable(L, "userInfoMeta");
lua_setmetatable(L, -2);
return 1;
}
// I have binded newUserInfo to the createUserInfo method.
// I have also created the metatable for this userInfo Object in the init method.
// luaL_newmetatable(L, "userInfoMeta");
// lua_pushstring(L, "__index");
// lua_pushvalue(L, -2);
// lua_settable(L, -3);
// luaL_register(L, NULL, userInstance_methods);
Please let me know if I am missing anything!
My LuaCode snippet:
local library = require('plugin.user')
local userInfo = library.newUserInfo()
print(userInfo.getUserName())
Update
I got rid of null, after using lua_upvalueindex(1) This is giving reference back to the user info instance.
UserInfo **userInfo = (UserInfo**)lua_touserdata(L,lua_upvalueindex( 1 ));
Hope it helps others too!
I think it may be the way your dealing with the userdata's metatable. Specifically, I think what you're returning from createUserInfo() is a table not a userdata. What I suggest is that you create the metatable once e.g. in luaopen, and then just set that on the new userdata. Something like this...
int createUserInfo(lua_State *L) {
UserInfo *userInfo = [[UserInfo alloc] init];
UserInfoData **userInfoData = (UserInfoData **)lua_newuserdata(L, sizeof(userInfo));
*userInfoData = userInfo;
luaL_getmetatable(L, "userInfoMeta");
lua_setmetatable(L, -2);
return 1;
}
LUALIB_API int luaopen_XXX(lua_State *L)
{
luaL_newmetatable(L,"userInfoMeta");
luaL_openlib(L, NULL, userInstance_methods, 0);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
...
lua_upvalueindex(1) has fixed the nil error.
UserInfo **userInfo = (UserInfo**)lua_touserdata(L,lua_upvalueindex( 1 ));
I want to explain in brief on what is actually happening. function(s) in C will get stack of params passed to the method. Lua online document has example of an Array, where all of its methods take first parameter of array instance. so, lua_touserdata(L,1) worked fine as the first parameter is the array instance.
Example from lua.org shows
a = array.new(10) --size 10
array.insert(a, 1, 1) --array.insert(instance, index, value).
lua_touserdata(L,1) works as the first param is the array instance.
In my case, I was invoking the method over instance without any params. So, the lua stack was empty in my C function and lua_touserdata(L,1) was throwing null.
Example:
a = array.new(10)
a.showValues() --the method is not over array. it is called on instance.
So, inorder to get access to the instance in showValues, I need to call lua_touserdata(L, lua_upvalueindex(1)). This will give the array instance object.
I'm trying to write a basic DST converter. I have a segmented control with 3 choices, their titles (surprisingly) are Distance, Speed and Time. I have 2 input text fields and a calculate button, as well as 2 labels for each text field with the type of measurement required and it's units. Making a selection on the segmented control should update the view accordingly. The variables have all been declared as IBOutlets, #property, #synthesize, and the code sits in an IBAction method, which is connected to the segmented control. The following code does not work, am I missing something completely obvious? (NSLog shows the correct title)
NSString *choice;
choice = [dstChoiceSegmentedControl titleForSegmentAtIndex: dstChoiceSegmentedControl.selectedSegmentIndex];
NSLog(#"Choice |%#|", choice);
if (choice == #"Distance") {
firstLabel.text = #"Speed:";
firstUnitsLabel.text = #"kts";
secondLabel.text = #"Time:";
secondUnitsLabel.text = #"hrs";
answerUnitsLabel.text = #"nm";
} else if (choice == #"Speed") {
firstLabel.text = #"Distance:";
firstUnitsLabel.text = #"nm";
secondLabel.text = #"Time:";
secondUnitsLabel.text = #"hrs";
answerUnitsLabel.text = #"kts";
} else if (choice == #"Time") {
firstLabel.text = #"Distance:";
firstUnitsLabel.text = #"nm";
secondLabel.text = #"Speed:";
secondUnitsLabel.text = #"kts";
answerUnitsLabel.text = #"hrs";
}
Thanks for your help (and I hope it's not some silly error that is staring me right in the face)!
You cannot compare strings this way. You need to do:
[choice isEqualToString:#"Distance"];
But if I were you, I'd check for the indicies instead.
edit: To explain it further: what you're doing with choice == #"Distance" is comparing a pointer with a string, which will not work. You need to call the string objects comparing method as shown above.