how to inherit model with json Mapping functionality? - ios

Hi I want to create model like below
is it possible to create model inheritance with Matle/JSON Model framework ?
ex.
#interface basePropertyModel : NSObject
#property (nonatomic,readwrite) int pid;
#property (nonatomic) contactModel *mContact; // contact is also model
#end
#interface projectModel : basePropertyModel
#property (nonatomic,retain) NSString *date_launch,*type_specifications;
end
Q.1)Please suggest me best way to use model
Q.2)Can i assign value of json response dict directly to my model as example ContactModel which can be directly assign json response dict.
Thanks & regards

Related

Creating a custom class in IOS Objective C

I have an existing project that requires porting a Swift Mock to to Objective C which I haven't used before. I have been trying to complete this so would value some help on the approach to take. I have tried several tutorials but I seem to have xcode sharing errors.
Error:
Xcode doesn't seem to recognise the class in the VC
Property 'assetName' not found on object of type '__strong id'
## Code to port to objective C
struct Asset {
let assetName: String
let assetColour: String
let assetValue: Int
let AssetSource: String
}
struct ExternalAsset {
let assetName: String
let assetColour: String?
let assetSupplier: String?
let assetValue: Int?
let assetMargin: Double?
}
Here is the attempt I made from Objective C from following som older tutorials
ExternalAsset.h
#interface ExternalAsset:NSObject
#property (nonatomic, strong)NSString *assetName;
#property (nonatomic, strong)NSString *assetColour;
#property (nonatomic, strong)NSString *assetSupplier;
#end
ExternalAsset.m
#import "ExternalAsset.h"
#implementation ExternalAsset
#end
in my calling class - I have the following:
AssetCatalogue.h
- (void)didPayforAsset:(ExternalAsset *)assetPaidFor // Error Message ( "Expected a Type")
{
NSMutableDictionary *paidItems = [#{
"AssetName": assetPaidFor.assetName,
// `Error: Property 'AssetName' not found on object of type '__strong id'
} mutableCopy];
}
#end

JSON To Model Mapping in Objective-C

I am trying to map the JSON I received to a model object in Objective-C.Before I always used ObjectMapper when I coded in swift. I can't seem to grasp the steps I need to go through to achieve the same kind of result when I used ObjectMapper.The problem is when using ObjectMapper you write the code where the mapping happens inside the model class such as;
Ex:
public struct Item: Mappable{
public var name: String?
public var id: Int?
public var description: String?
public init?(map: Map) {
}
init(){
}
public mutating func mapping(map: Map) {
name <- map["name"]
id <- map["id"]
description <- map["description"]
}
}
I understand that I have to write some kind of underlying helper classes to achieve the same kind of functionality but I can't seem to manage because I don't understand the concept at all. I could not find or even if I did,I could not understand how to do it. Please Help.
My model class would look like this in objective-c Im guessing:
#interface BBKProductMetaData : NSObject
#property (nonatomic, strong,nonnull, readonly) NSString *name;
#property (nonatomic, strong,nonnull, readonly) NSInteger *id;
#property (nonatomic, assign,nonnull, readonly) NSString *description;
#end
What am I supposed to do to map my JSON response to this model.
Objective-c is not much advance as Swift. So you have to remember some things, like
If you are creating models, that means it must be accessible to other class, so you have to write that all properties and other declaration things which you want to access to other classes should be in .h file not in .m file
In objective-c you have to import all model classes to header, which you want to access.

AWS API Gateway Client for iOS returns error "Failed to serialize the body JSON"

I defined my REST API using AWS API Gateway and generated client code for iOS. When I call a method the SDK outputs this error message:
AWSiOSSDKv2 [Error]
AWSAPIGatewayClient.m line:190
__118-[AWSAPIGatewayClient invokeHTTPRequest:URLString:pathParameters:
queryParameters:headerParameters:body:responseClass:]_block_invoke_2 |
Failed to serialize the body JSON.
(null)
What is wrong?
Easy!
Make sure your AWSModel has the same number of class members as the number of JSON key paths property keys. Mine has no class member and 2 property keys.
Make sure the name of each property key matches the name of the class member. Again I had a key for "code" and no matching "code" property.
For clarity, look at the JSONKeyPathsByPropertyKey function. If you see #"abc": #"def" then you must have a property "abc" in your class otherwise the JSON conversion will fail.
// Sample JSON returned by AWS API Gateway
{"code":200, "message":"OK", "data":{"phone":"(555) 555-1234"}}
// APISample.h
#import
#import
#interface APISample : AWSModel
// We count 4 class members
#property (nonatomic, strong) NSNumber *code;
#property (nonatomic, strong) NSString *message;
#property (nonatomic, strong) NSDictionary *data;
#property (nonatomic, strong) NSNumber *phone;
#end
// APISample.m
#import "APISample.h"
#implementation APISample
// We count 4 property keys
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return #{
#"code": #"code",
#"message": #"message",
#"data": #"data",
#"phone": #"data.phone"
};
}
Tip: Notice how you can access a branch (data as NSDictionary) and traverse the document structure with dot notation (data.phone).
Bonus: a working Swift example just for you.
// Swift sample code to access AWS API Gateway under iOS
// Create a client with public access
var client : APISampleClient = APISampleClient.defaultClient()
// Comment next line if your API method does not need API key
client.APIKey = "Your API key"
client.SampleMethodGet().continueWithBlock { (task : AWSTask) -> AnyObject? in
if task.error != nil {
print("Error \(task.error)")
}
else if task.result != nil {
let output = task.result as! APISample
print("Success \(output)")
}
return nil
}

Swift instance variable with protocol

I have to translate the following lines of Objective-c code into swift. This is a sample from the Objective-c JSONModel-Framework where the Optional protocol provided by the Framework is applied to an instance variable of type NSString. I found a related post but i didn't managed to achieve it. With my MYModel.swift implementation Xcode complains Cannot specialize non-generic type NSString
thx for your help!
MYModel.swift
#objc(MYModel) public class MYModel : JSONModel {
...
public var name : NSString<Optional>
...
}
MYModel.h
#interface MYModel : JSONModel
...
#property (strong, nonatomic) NSString<Optional>* name;
...
JSONModel.h
...
/**
* Protocol for defining optional properties in a JSON Model class. Use like below to define
* model properties that are not required to have values in the JSON input:
*
* #property (strong, nonatomic) NSString<Optional>* propertyName;
*
*/
#protocol Optional
#end
...
The < and > are not for conforms to protocol. It is for Types with generics like Array:
Array<T>
so you can write var a: Array<String>.
You want something else, a variable should be a Type String and conform to the protocol
You can extend String with the protocol and add the needed functions yourself.
Since your Optional protocol is empty, it is enough to write:
extension NSString: Optional {} // you can use String if you like
To create the protocol write in Swift:
protocol Optional {}
You can Objective-C create the protocol, too.
You should not use Optional, because there is already one, but because Swift has namespacing, it works.
You could of course write something like that:
extension NSString: JsonOptProtocol {}
protocol JsonOptProtocol {} // or create that in Objective-C like you did
Documentation link.
Optional is a type declared in the standard library of Swift, at the moment JSONModel is not compatible with Swift because of this.

Getting error use of undeclared identifier "value" when assigning parameter to variable

When I assign value to age, I get this error:
#interface Person : NSObject
{
int age;
}
-(void)setAge;
#end
I tried to use self.age, yet it did not work
Here is my .m file:
#implementation Person
-(void)setAge(int)value
{
age = value;
}
#end
I tried several differnet things. ..I get this error when I type this: age = value; do you know why this is?
You should add:
-(void)setAge:(int)value;
In the header file because the current method specification you have there doesn't have a parameter.
Your method in the implementation should also have the same spec as it's missing a colon currently.
You have actually declared one method (-setAge) and implemented another (-setAge:, note the colon). You should really declare age as a property and avoid explicit ivars as much as possible. Also, I hope you have properly formatted the class in your real code.
#interface Person : NSObject
#property (nonatomic) int age;
#end
#implementation Person
-(void)setAge:(int)value
{
_age = value;
}
#end
Note that it is no longer necessary to explicitly #synthesize properties, and they automatically synthesize with an underscored ivar.

Resources