This is a generic design pattern regarding accessing model object value - ios

In iOS, I have three controllers A,B,C. I have a model object and I am storing text box value in model property of an object and then I am storing model object in database where all this things happening in controller A. In controller C, I am trying to access that model object property, it shows me nil. I don't know why. Below is the example:
I have a model.m class like below
#implementation model:NSObject
#property(nonatomic)NSString *firstname;
A.m class
model m=[model alloc]init];
m.firstname=#"stackoverflow";
// and saving the "m" in PARSE framework which internally stores in database.
C.m class
model m =[model alloc]init];
NSLog(#"%#",m.firstname);// shows null value
what is the right way to access it? Please help me in this case.

You should use a Single Instance

Related

How to iterate over the properties of my models in objective c?

I want to iterate over the properties of my models in Objective-C. I tried this. Created PropertyUtil class with method classPropsFor:(Class)klass. Please find the attachment. Used objc/runtime.h. The code which I got from the net. In my viewcontroller I am doing this. [PropertyUtil classPropsFor:[self.user class]];. self.user is User model class. What I want to know is how can i iterate over the properties of my models, let's username, password and those values.
You may want to manually list all properties your model has.
Just add a method to your model:
+(NSArray*) propList {
return #[#"prop1", #"prop2"];
}
Then just use key-value coding to get the value
[someObject valueForKey:#"prop1"];
That's pretty straight and simple way if you wish to avoid Obj-C meta functions. Since you add your properties manually anyway, you may also add them in your list as well.
That's of course, if you don't have a large amount of models already and you wish do them all at once.

Create an instance of a class inside its own self

Here's the situation.
I have a swift model class file that contains all the variables for a weather forecast (min temperature, max temperature, humidity, etc).
The class also contains the function that downloads all the data from the API.
My question is, is it possible to create an array of the class inside the class itself, so that I can append a number of objects (of the same class itself) based on the number of days of forecast the API sends back?
If so, can you tell me how it could be achieved?
The other option I have that totally works, is to do the API downloading and parsing outside of the forecast class (in the ViewController) but that would make my ViewController messy.
You shouldn't call the API to get all the weather's datas in your model but in a dedicated class.
Also, you shouldn't parse and store the datas inside your model.
In your model, you only need to have all the attributes of your object and methods.
Maybe you can create an Helper class where you implements all this methods and store the datas.
There's nothing preventing you from referencing a class name within its definition. So you can do something like this:
class Foo {
var boz = [Foo]() // you can append to this array as needed
}

How do I indicate to CoreData that an object has changed?

In my CoreData model, I have an entity called Contact. It has an attribute called profileImage, with the type set to Transformable.
In the Contact class (a subclass of NSManagedObject), I've changed profileImage from being a generic id to being an UploadedImage:
#property (nonatomic, retain) UploadedImage * profileImage;
The UploadedImage class has a few properties of its own.
The problem is that CoreData doesn't know when the properties on the UploadedImage object have changed. If only those properties are changed, the willSave method is never called on the Contact object when the managed object is saved. It works as expected if I change any other property on the Contact object: it just doesn't "see" changes to anything on the UploadedImage object within the Contact object.
What's the correct way to indicate that the managed object needs to be saved? Should I manually call willChangeValueForKey: and didChangeValueForKey: for the key 'profileImage' on my Contact object?
Edit to clarify a couple things
Contact is a CoreData entity, but the ImageUpload class is NOT.
CoreData will save the data in the ImageUpload object (because I implemented the NSCoding protocol methods, I think). If I change a property on the ImageUpload object, AND change a property on the Contact object, the Contact is saved, and that changed value persists on the ImageUpload object when the Contact is loaded from CoreData again.
Unless there's another way I'm not aware of, it sounds like marking the NSManagedObject as dirty is the way to go. You can do that using a separate dirtyFlag attribute, or by simply using the profileImage attribute itself.
One way to automate this would be KVO. You observe all properties of UploadedImage in the Contact class, and then just call self.profileImage = self.profileImage. I'm not sure if this is optimized by the compiler. If it is, you can also call willChangeValueForKey: and didChangeValueForKey:, which should trigger it. If Core Data noticed that the object didn't actually change, you can try to implement NSCopying and assign a copy of the original UploadedImage.
I don't believe Core Data will persist changes made to the subclass. The contract in Core data is between the parent entity and Core Data, so Core Data only responds to changes made to the properties in the entity class.
You can get around this by making that property a NSDictionary in the Entity and in the subclass add the image object to the dictionary.
Expanding upon Scott's solution (no copy necessary!), here is a method for Swift that works with any field:
static func markDirty<C, T>(_ obj: C, _ keyPath: ReferenceWritableKeyPath<C, T>) {
obj[keyPath: keyPath] = obj[keyPath: keyPath]
}
Used like so:
NSManagedObject.markDirty(playlist, \.rules)
Unfortunately it's not possible right now to define it as an instance method, due to limitations with generics.

Cross-Store weak relationship with Fetched Properties?

I would like to separate my reference data from my user data in my Core Data model to simplify future updates of my app (and because, I plan to store the database on the cloud and there is no need to store reference data on the cloud as this is part of my application). Therefore, I've been looking for a while for a way to code a cross-store relationship using fetched properties. I have not found any example implementations of this.
I have a Core Data model using 2 configurations :
data model config 1 : UserData (entities relative to user)
data model config 2 : ReferenceData (entities relative to application itself)
I set up 2 different SQLite persistent stores for both config.
UserData config (and store) contains entity "User"
ReferenceData config (and store) contains entities "Type" and "Item".
I would like to create two single-way weak relationships as below :
A "User" has a unique "Type"
A "User" has many "Items"
Here are my questions :
How do I set up my properties?
Do I need 2 properties for each relation (one for storing Unique ID and another to access my fetched results)?
Could this weak relationship be ordered?
Could someone give me an example implementation of this?
As a follow-on to Marcus' answer:
Looking through the forums and docs, I read that I should use the URI Representation of my entity instance instead of objectID. What is the reason behind this?
// Get the URI of my object to reference
NSURL * uriObjectB [[myObjectB objectID] URIRepresentation];
Next, I wonder, how do I store my object B URI (NSURL) in my parent object A as a weak relationship? What attribute type should I use? How do I convert this? I heard about archive... ?
Then, later I should retrieve the managed object the same way (by unconvert/unarchive the URIRepresentation) and get Object from URI
// Get the Object ID from the URI
NSManagedObjectID* idObjectB = [storeCoordinator managedObjectIDForURIRepresentation:[[myManagedObject objectID] URIRepresentation]];
// Get the Managed Object for the idOjectB ...
And last but not least, shouId I declare two properties in my entity A, one for persisting of URI needs and another for retrieving direclty object B?
NSURL * uriObjectB [objectA uriObjectB];
ObjectB * myObjectB = [objectA objectB];
As you can read, I really miss some simple example to implement thes weak relationships ! I would really appreciate some help.
Splitting the data is the right answer by far. Reference data should not be synced with the cloud, especially since iCloud has soft caps on what it will allow an application to sync and store in documents.
To create soft references across to stores (they do not need to be SQLite but it is a good idea for general app performance) you will need to have some kind of unique key that can be referenced from the other side; a good old fashioned foreign key.
From there you can create a fetched property in the model to reference the entity.
While this relationship cannot be ordered directly you can create order via a sort index or if it has a logical sort then you can sort it once you retrieve the data (I use convenience methods for this that return a sorted array instead of a set).
I can build up an example but you really are on the right track. The only fun part is migration. When you detect a migration situation you will need to migrate each store independently before you build up your core data stack. It sounds tricky but it really is not that hard to accomplish.
Example
Imagine you have a UserBar entity in the user store and a RefBar entity in the reference store. The RefBar will then have a fetchedProperty "relationship" with a UserBar thereby creating a ToOne relationship.
UserBar
----------
refBarID : NSInteger
RefBar
--------
identifier : NSInteger
You can then create a fetched property on the RefBar entity in the modeler with a predicate of:
$FETCHED_PROPERTY.refBarID == identifier
Lets name that predicate "userBarFetched"
Now that will return an array so we want to add a convenience method to the RefBar
#class UserBar;
#interface RefBar : NSManagedObject
- (UserBar*)userBar;
#end
#implementation RefBar
- (UserBar*)userBar
{
NSArray *fetched = [self valueForKey:#"userBarFetched"];
return [fetched lastObject];
}
#end
To create a ToMany is the same except your convenience method would return an array and you would sort the array before returning it.
As Heath Borders mentioned, it is possible to add a sort to the NSFetchedProperty if you want but you must do it in code. Personally I have always found it wasteful and don't use that feature. It might be more useful if I could set the sort in the modeler.
Using the ObjectID
I do not recommend using the ObjectID or the URIRepresentation. The ObjectID (and therefore the URIRepresentation of that ObjectID) can and will change. Whenever you migrate a database that value will change. You are far better off creating a non-changing GUID.
The weak relationship
You only need a single value on the M side of the relationship and that stores the foreign identifier. In your object subclass you only need to implement accessors that retrieve the object (or objects).
I would go with just one store.
For storing stuff in the cloud, you will anyway have to serialize the data, either as JSON or SQL statements, or whatever scheme you prefer.
You will need a local copy of the data on the user's device, so he can access it quickly and offline. The cloud store can have only the user entity, while the local store (part of the app) can also have the reference entity.
I have a similar project with a huge reference store (20000 records) with geographic information, and user generated content ("posts"). I use a single store. When I ship the app, the "posts" entity is also defined but empty. When I update the data model I simply re-generate the whole reference store before shipping.
I see absolutely no reason to go for a cross store solution here.

Objective-C get a class property from string

I've heard a number of similar questions for other languages, but I'm looking for a specific scenario.
My app has a Core Data model called "Record", which has a number of columns/properties like "date, column1 and column2". To keep the programming clean so I can adapt my app to multiple scenarios, input fields are mapped to a Core Data property inside a plist (so for example, I have a string variable called "dataToGet" with a value of 'column1'.
How can I retrieve the property "column1" from the Record class by using the dataToGet variable?
The Key Value Coding mechanism allows you to interact with a class's properties using string representations of the property names. So, for example, if your Record class has a property called column1, you can access that property as follows:
NSString* dataToGet = #"column1";
id value = [myRecord valueForKey:dataToGet];
You can adapt that principle to your specific needs.

Resources