Initialize a subclass of NSManagedObject - ios

I have a question about CoreData and NSManagedObject.
I receive a NSDictionary in my ClientRESTClass (I use AFNetworking 2.0) so I have a Json data in this NSDictionary.
For this object type I use a my protocol with two methods that these objects must implement:
- encodeFromJson //(instance to JSON)
- decodeFromJson //(from json I create an instance)
Now I have a myObj as subclass of NSManageObject that implements this protocol.
1) In the decodeFromJson how can I to generate an instance of myObj? Is necessary to use in this point a context? Is possible to use a simple init?
2) At this level I receive data from server an I create instance of these object. I pass this instance to the caller and he will decide whether to save the object or if you do not save it in CoreData.
So, If I have to use a contex, how can I discard objects that I placed in the context?

You should not create an NSManagedObject directly, you should use the NSNSEntityDescription's insertNewObjectForEntityForName -- see: Apple Docs.

Related

Cache Array of Custom Objects in Swift3

I need to persist an array of custom objects from session to session for a user. The array will be filled with 1-14 fairly simple and lightweight custom swift objects like so:
[Obj1, Obj2, Obj3]
What I want to do is when viewWillDisappear is called, persist this data so that when the user comes back to the screen, I can use these exact objects again. What is the best way to do this? I've looked into using core data, but I don't want to setup a data model for these objects, just store them as is without any relationships or anything.
Please note that the app makes use of a very computationally taxing algorithm, of which these objects play a central role. As such, I need to keep these objects as light as possible. Therefore, I don't want to make the objects conform to NSCoding as it isn't necessary to the central role of the object
If making your class an Objective-C class that conforms to NSCoding proves to actually have a substantial performance impact (I'm skeptical), then you can make a second container that subclasses NSCoding that's used solely for storage. Add an initializer to your current lightweight Swift class/struct that initializes the instance from this container object, and vice versa. Any time you need to serialize/deserialize, you just use this container object as an intermediate.
This buys you the functionality at minimal cost when reading/writing, but leaves regular usage performance unaffected.
If you can make the object a subclass of NSObject then you can have it conform to NSCoding and use NSKeyedArchiver and NSKeyedUnarchiver to serialize and deserialize your objects.

How can I save a Swift dictionary structure?

I have a Swift dictionary structure ([String : CustomObject]) that I need to save once and then reload later whenever the application launches. How do I go about saving and reloading a dictionary using Swift?
you can convert the Dictionary to NSData link here and then save it to NSUserDefaults as it is here
If you have custom objects then you need to make them conform to the NSCoding protocol. This means implementing the methods encodeWithCoder and initWithCoder. It comes down to deconstructing the state values of your object to data types that are either "property list" types, or types that also conform to NSCoding. Your implementation of encodeWithCoder can, encode it's properties that are objects that conform to NSCoding by calling encodeObject:forKey:

Implement a Swift protocol by automatically mapping method calls to keys in a dictionary

In Objective C I have previously been able to implement an automatic mechanism to allow an object with a private NSDictionary property to implement a simple protocol by automatically converting method invocations to dictionary 'valueForKey' requests, and passing these to the dictionary that has the appropriate key:value.
For example, I would have an object 'ABCArtist', which would implement the artistProtocol. This protocol has a method -(NSString*)artistName; and the 'ABCArtist' object would implement this method by returning [self.privateDictionary valueForKey:artistName];
This process relied on overriding the NSObject methods:
- (void)forwardInvocation:(NSInvocation *)invocation;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector;
- (id)forwardingTargetForSelector:(SEL)aSelector;
I have tried to apply the same process in Swift, however I am unable to use this as I get the compiler error:
'NSInvocation' is unavailable in Swift: NSInvocation and related APIs
not available
Is there any way that anyone has found to implement a protocol by automatically querying a dictionary for a value with the same name as the protocol method?
The use case for this is in mapping to a dictionary of JSON content returned from an API, if this automatic mapping can be accomplished, I only need to write the protocol, and forward it to the generated JSON dictionary.
That kind of dynamic handling of arbitrary messages at runtime can only be done in Objective-C. For one thing, calls to pure Swift methods don't even go through the Objective-C dynamic dispatch mechanism. So it would have to be an #objc method, and the forwardInvocation: logic will have to be implemented in Objective-C.

How do I save a custom c++ class object to NSUserDefaults?

I want to add a C++ Class object into NSUserDefaults. If I add it directly, it crashes.
How do I add c++ Class object to NSUserDefaults?
NSUserDefaults supports some NSObject-based classes to be encoded out of the box. Proper way to save custom NSObject classes into NSUserDefaults instance is to encode them into NSData and save it.
In your case, since you have a C++ class, you could either wrap it's data to an NSObject (NSDictionary maybe) or implement a class <-> string serialisation and deserialisation, saving a string object into the NSUserDefaults instance.

How to store custom object in User Defaults - IOS

I created one custom class & created object for that class. I want to store that object into NSUserDefault. I am getting error while set the object into userfaults. How can I set?
You have to implement the NSCoding protocol in your class & implement the protocols methods.
This is simply serialization. While storing the object you should serialize(NSKeyedArchiver) the class & same as retrieval you should unserialize(NSKeyedUnArchiver) that object.
the methods are
(void)encodeWithCoder:(NSCoder *)aCoder;
(id)initWithCoder:(NSCoder *)aDecoder;
As the documentation states:
A default object must be a property list, that is, an instance of (or
for collections a combination of instances of): NSData, NSString,
NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any
other type of object, you should typically archive it to create an
instance of NSData.
The simplest way of creating an instance of NSData is by using an NSKeyedArchiver.
The most probably reason is that you have something hard to archive in your structure.
Here is a quote from the NSUserDefaults Class Reference that you might find useful:
The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.
Edit.
Beaten to the punch by Stephen, give the man a prize :)

Resources