I have been really deep thinking about a general way of creating "data model", and been jiggling with best practices and MVC pattern. Currently I am using a singleton pattern to get my httprequest and json parser (which comes as NSDictionary). Now rather than accessing this parser directly, I was hoping to make a Data model that can be binded through this.
However, I have been struggling if there is an easy way to do that rather than assigning manually "[myObj setValue:[jsonDict objectForKey:#"name"]];" where myObj tends to be a simple NSString object.
Since NSDictionary is a nice KVC concept, how can I utilize this to enrich a better style of data model in which I can generally access myObj.name or myObj.address entity than "[myObj setValue:[jsonDict objectForKey:#"name"]];" behavior.
I have looked into "Core Data" model, however the current design doesn't require to store anything locally, but just within memory for security reasons.
Any good ideas or best practices solution here will be really helpful.
Just create your classes. Then crate an class that will serialize the data from your dictionaries to your object.
Let say you create an class Person that has properties firstName and lastName. Then you crate a Class like PresonController, that will do manage the person objects, and in it create class methods like
+(Preson *)personFromDictionary:(NSDictionary)peseonDictionary;
And every time you need to create an person from an dictionary you will do
Person *newPerson = [PersonController personFromDictionary:yourPersonDictionary];
And then in the code you just access the properties of the Person object
NSLog(#"Person first name:%#",newPerson.firstName);
Hope I was clear enough for you.
Related
For example I have a field that I want to access in my app view. I have this provider
class User with ChangeNotifier{
String userNick = "test";
String get getName() => userNick;
}
What will be the difference, if I access the nick this way in my app vs getter?
context.watch<User>().userNick;
vs
context.watch<User>().getName();
If I don't use the getter and my userNick changes, will I not see it refreshing in my app or?
Getters/setters are preferred for use the data properly. If you use the data directly, you can update it when you even don't wanna update it and this type of logical mistakes takes too much time to detect and fix. Also, it is safe way to manipulate the data.
Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
from: https://en.wikipedia.org/wiki/Object-oriented_programming
For more, you can search for encapsulation online.
I'm looking for a way of condensing some of my AS3 code to avoid almost duplicate commands.
The issue is that I have multiple variables with almost the same name e.g. frenchLanguage, englishLanguage, germanLanguage, spanishLanguage
My Controller class contains public static variables (these are accessed across multiple classes) and I need a way to be able to call a few of these variables dynamically. If the variables are in the class you are calling them from you can do this to access them dynamically:
this["spanish"+"Language"]
In AS3 it's not possible to write something like:
Controller.this["spanish"+"Language"]
Is there any way to achieve this? Although everything is working I want to be able to keep my code as minimal as possible.
It is possible to access public static properties of a class this way (assuming the class name is Controller as in your example:
Controller['propertyName']
I'm not sure how this helps to have "minimal code", but this would be a different topic/question, which might need some more details on what you want to achive.
Having said that, I like the approach DodgerThud suggests in the comments of grouping similar values in a (dynamic) Object or Dictonary and give it a proper name.
Keep in mind, that if the string you pass in as the key to the class or dynamic object is created from (textual) user input you should have some checks for the validity of that data, otherwise your programm might crash or expose other fields to the user.
It would make sense to utilize a Dictionary object for a set of variables inherited: it provides a solid logic and it happens to work...
I do not think this is what you are trying to accomplish. I may be wrong.
Classes in AS3 are always wrapped within a package - this is true whether you have compiled from Flash, Flex, Air, or any other...
Don't let Adobe confuse you. This was only done in AS3 to use Java-Based conventions. Regardless, a loosely typed language is often misunderstood, unfortunately. So:
this["SuperObject"]["SubObject"]["ObjectsMethod"][ObjectsMethodsVariable"](args..);
... is technically reliable because the compiler avoids dot notation but at runtime it will collect a lot of unnecessary data to maintain those types of calls.
If efficiency becomes an issue..
Use:
package packages {
import flash.*.*:
class This implements ISpecialInterface {
// Data Objects and Function Model
// for This Class
}
package packages {
import...
class ISpecialInterface extends IEventDispatcher
This is more of a generalized question as I have yet to write the code for the question I am asking. Before I get started writing the code I wanted to make sure I am on the right track and possibly getting suggestions for better ways to do what I want to do. Basically right now I have a core data model setup in a way that I think is correct for what I am trying to do and just need some guidance on a very specific part of the code but want to make sure overall I created it correctly.
The first part to the question is more of a clarification on how relationships work in core data. Right now I have 5 entities and to make sure I have the correct idea on how it works I will use a few examples to make sure I am on the right track.
So lets save I have an entity I called name. Within that Name entity that contains only a name attribute. Next I have an entity that has classes, that each have a boolean of true or false to determine which class it is. These 2 are related in a inverse relationship of Name entity having a to one relationship and the Classes having a to many relationship because multiple names can have multiple classes but each name can only have 1 class. If I am right on this one that means I full understand core data relationships!
Now the second part of the question is related to the booleans in the class. I have the Class entity which is like I said a boolean containing a true false set as default to false. When the user selects one of the class buttons before presenting the popover where they actually give the name of the class selected it saves the boolean to true then passes that data over to the popover Name view controller. I am very unsure as to how to do this as it isn't a widely asked question on here nor have I been able to find any info through researching. I am one of those people who needs to actually learn by clear examples....any help with this would be appreciated! Sorry I don't have any example code for this.
The first part seems correct. The ManagedObject of your Class CoreDataObject should have an NSSet property which will contain the names (as the Class can have multiple names)
For the second part, Core Data uses objects. When you 'get' the data from Core Data it will be a (probably extended) NSManagedObject (named Class in our case). You can send this object as a parameter just as you would do with any other object and use it as you would use any other object :-). For example looping over de NSSet Names
func iterateOverNames(someClass: Class) {
for name: Name in someClass.names {
// do stuff
}
}
You can check these links for more information:
https://realm.io/news/jesse-squires-core-data-swift/
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/index.html
The title may seems confusing, but it's not easy to describe the question in few words. Let me explain the situation:
We have a web application project, and a calculation engine project. The web application collect user input and use the engine to generate some result, and represent to user. Both user input, engine output and other data will be persisted to DB using JPA.
The engine input and output consist of objects in tree structure, example like:
Class InputA {
String attrA1;
List<InputB> inputBs;
}
Class InputB {
String attrB1;
List<InputC> inputCs;
}
Class InputC {
String attrC1;
}
The engine output is in similar style.
The web application project handle the data persistence using JPA. We need to persist the engine input and output, as well as some other data that related to the input and output. Such data can be seem as extra fields to certain class. For example:
We want to persist extra field, so it looks like:
Class InputBx extends InputB{
String attrBx1;
}
Class InputCx extends InputC{
String attrCx1;
}
In Java OO world, this works, we can store a list of InputBx in InputA, and store a list of InputCx in InputBx because of the inheritance.
But we meet trouble when using JPA to persist the extended objects.
First of all, it requires the engine project to make their class become JPA entities. The engine was working fine by itself, it accept correct input and generate correct output. It doesn't smell good to force their model to become JPA entities when another project try to persist the model.
Second, the JPA doesn't accept the inherited objects when using InputA as the entry. From JPA point of view, it only know that InputA contains a list of InputB, and not possible to persist/retrieve a list of InputBx in object of InputA.
When trying to solve this, we had come up 2 ideas, but neither one satisfied us:
idea 1:
Use composition instead inheritance, so we still persist the original InputA and it's tree structure include InputB and InputC:
Class InputBx{
String attrBx1;
InputB inputB;
}
Class InputCx{
String attrCx1;
InputC inputC;
}
So the original input object tree can be smoothly retrieved, and InputBx and InputCx objects needs to be retrieved using the InputB and InputC objects in the tree as references.
The good thing is that no matter what changes made to the structure of the original input class tree (such as change attribute name, add/remove attributes in the classes), the extended class InputBx and InputCx and their attributes automatically synchronized.
The drawback is that this structure increases the calls to the database, and the model is not easy to use in the application(both back end and front end). Whenever we want related information of InputB or InputC, we need to manually code to search the corresponding object of InputBx and InputCx.
idea 2:
Manually make mirror classes to form a similar structure of the original input classes. So we created:
Class InputAx {
String attrA1;
List<InputBx> inputBs;
}
Class InputBx {
String attrB1;
List<InputCx> inputCs;
String attrBx1;
}
Class InputCx {
String attrC1;
String attrCx1;
}
We could use this as model of the web application, and the JPA entities as well. Here's what we could get:
Now the engine project can be set free, it doesn't need to bind to how the other projects persist these input/output objects. The engine project is independant now.
The JPA persistence works just fluent, no extra calls to database is required
The back end and front end UI just use this model to get both original input objects and related information with no effort. When trying use engine to perform calculation, we can use a mapping mechanism to transfer between the original objects and extended objects.
The drawback is also obvious:
There is duplication in the class structure, which is not desired from the OO point of view.
When considering it as DTO to reduce the database calls, it can be claimed as anti-pattern when using DTO in local transfer.
The structure is not automatically synchronized with the original model. So if there are any changes made to the original model, we need to manually update this model as well. If some developers forget to do this, there will be some not-easy-to-find defects.
I'm looking for the following help:
Is there any existing good/best practices or patterns to solve similar situation we meet? Or any anti-patterns that we should try to avoid? References to web articles are welcome.
If possible, can you comment on the idea 1 and idea 2, from the aspect of OO design, Persistence practices, your experience, ect.
I will be grateful for your help.
NSManagedObject *entryObj = [self.fetchedResultsController
objectAtIndexPath:indexPath];
entryObj consists of four String attributes.
If I NSLog entryObj, I get the information I want. I cannot figure out how to access each of these properties individually. I read a similar post where the solution was to call "entity." I cannot figure out how to use "entity" to access a specific attribute.
Any ideas? References? Tutorials?
Thanks in advance.
Properties on managed objects are KVC/KVO compliant so you can access them via:
[entryObj valueForKey:#"name"]
Alternatively you can generate a custom Core Data class with real properties to access these values. See this documentation for more information. The Xcode core data modelling tool can generate these classes for you. While you have the model open, choose "File->New File" and you should see a "Managed Object Class" item. Choose this and select the entities you wish to generate classes for.
Once you have done this and the core data entities have their class name set appropriately, you just cast the NSManagedObject to an instance of your new class and access its properties, i.e.
MyObject *entryObj = (MyObject *) [self.fetchedResultsController
objectAtIndexPath:indexPath];
NSLog(#"Property is %#", entryObj.whatever);
If you build your NSManaged objects with the designer then you can export model classes. From the xcdatamodel do File/New File then pick CocoaTouch Class/Managed Object Class. Next then Next then tick each of your classes. Leave generate accessors and generate obj-c 2.0 properties ticked and click finished.
Now you can include the generated files in your projects and use dot accessor syntax.
Alternatively use [entryObject valueForKey:#"keyname"]; but I prefer to stick to the dot accessor syntax where possible.
For generating real classes with properties to call from your object model, I highly recommend using mogenerator:
http://github.com/rentzsch/mogenerator
That's the main project, but the easy to download installer is here:
http://rentzsch.github.com/mogenerator/
You also get primitive value accessors for numeric types, for free.