I am leaning objective-c, and as shown below in the code, I created an interface with a private instance variable section. In the main.m, a pointer instance variable was created as shown below. what I want to know is how to send a message to one of private instance variable? Something as the following:
[ptr->_address XXX]..IS IT POSSIBLE
2- and how to initialise the private instance variables using
[[xxx alloc] initWithxxx]……IS IT POSSIBLE??
main.m
MeAsImpl *ptr = [[MeAsImpl alloc] initWithCountry:#"DEU" andCity:#"KA" andAddress:#"xyzstrasse7"];
NSLog(#"chip:[ %# ]", ptr->_address);
NSLog(#"chip:[ %p ]", structChipInitializerSegment);
NSLog(#"chip:[ %# ]", structChipInitializerSegment->chipName.self);
NSLog(#"chip:[ %p ]", structChipInitializerSegment->chipName.self);
NSLog(#"chip:[ %p ]", structChipInitializerSegment->numOfTotalChannels);
.h:
#import "ProtocolKidsSchedules.h"
#ifndef MeAsImpl_h
#define MeAsImpl_h
#endif /* MeAsImpl_h */
#interface MeAsImpl : NSObject<ProtocolKidsSchedules> {
id<ProtocolKidsSchedules> _signee;
NSString *_country;
NSString *_city;
NSString *_address;
}
#property (nonatomic, retain) id<ProtocolKidsSchedules> signee;
#property (nonatomic, retain) MeAsImpl *owner;
#property (nonatomic, retain) NSString *country;
#property (nonatomic, retain) NSString *city;
#property (nonatomic, retain) NSString *address;
-(NSString *) signeeOfTheContract: (id<ProtocolKidsSchedules>) signee;
-(id) initWithCountry: (NSString *) country andCity: (NSString *) city andAddress: (NSString *) address;
-(id) initWithOnlyCity: (NSString *) city;
-(id) initWithOnlyAddress: (NSString *) address;
#end
.m
#import <Foundation/Foundation.h>
#import "MeAsImpl.h"
#implementation MeAsImpl
#synthesize country, city, address;
-(BOOL)areChoresCompleted:(BOOL)completed {
return completed;
}
-(BOOL)areHomeWorkCompleted:(BOOL)completed {
return completed;
}
-(BOOL)doDerserveCookies:(BOOL)doDeserve {
return doDeserve;
}
-(NSString *)signeeOfTheContract:(id<ProtocolKidsSchedules>)signee {
return #"Signee is: ";
}
-(id)initWithCountry:(NSString *)country andCity:(NSString *)city andAddress:(NSString *)address {
self->_countery = country;
self->_city = city;
self->_address = address;
return self;
}
-(id)initWithOnlyCity:(NSString *)city {
self->_city = city;
return self;
}
-(id)initWithOnlyAddress:(NSString *)address {
self->_address = address;
return self;
}
#end
Related
I am new to RestKit and an Objective-C newbie. The JSON that I would like to turn into Objective-C objects has the following format.
{
"id":1,
"ron95":700.0,
"ron92":700.0,
"dieselNormal":700.0,
"dieselSpecial":700.0,
"postDate":1435465383000
}
In Java, the JSON would be represented like this:
public class Price {
private Long id;
private Double ron95;
private Double ron92;
private Double dieselNormal;
private Double dieselSpecial;
private java.util.Date postDate;
...
}
What would the mapping Objective-C class be like and how would you do the mapping using RestKit?
Edit: This is what I think my Objective-C representation should look like. Correct me if I am wrong.
Price.h
#import <Foundation/Foundation.h>
#interface Price : NSObject {
NSInteger id;
double ron95;
double ron92;
double dieselNormal;
double dieselSpecial;
NSDate *postDate;
}
#property (nonatomic) NSInteger id;
#property (nonatomic) double ron95;
#property (nonatomic) double ron92;
#property (nonatomic) double dieselNormal;
#property (nonatomic) double dieselSpecial;
#property (nonatomic, retain) NSDate *postDate;
#end
Price.m
#import "Price.h"
#implementation Price
#synthesize id;
#synthesize ron95;
#synthesize ron92;
#synthesize dieselNormal;
#synthesize dieselSpecial;
#synthesize postDate;
#end
I have been looking into this for a while. I decided to write my own solution. It is very simple and built upon existing Apple functionality. Just go to github and copy the source to your project. Have your Price class inherit from GSObject instead of NSObject.
Write a category for NSDate class with this class method:
+(id) initWithJsonValue:(NSString*)jsonValue
Here is where you would convert the date string
"postDate":1435465383000
to an NSDate probably using a date formatter.
See here: https://github.com/gslinker/GSObject
And here: http://digerati-illuminatus.blogspot.com/2016/01/objective-c-and-json-convert-subclass.html
Here is a sample that I made, notice it has an NSDate object as well.
For your data model object have it inherit from GSObject instead of NSObject. Here is an example of ThingOne with inherits from GSObject:
ThingOne* object1 = [[ThingOne alloc] init];
object1.name = #"John Jones";
NSData* jsonData1 = [object1 toJsonDataWithOptions:NSJSONWritingPrettyPrinted];
NSString *jsonString1 = [object1 toJsonStringWithOptions:NSJSONWritingPrettyPrinted];
NSDictionary<NSString *,id> *dict1 = [GSObject dictionaryWithValues:object1];
NSString *roundTripJson1 = [object1 toJsonStringWithOptions:NSJSONWritingPrettyPrinted];
//
// ThingOne.h
// JasonStuff
//
// Created by Geoffrey Slinker on 12/28/15.
// Copyright © 2015 Slinkworks LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "GSObject.h"
#import "ThingTwo.h"
#interface ThingOne : GSObject
#property (nonatomic, retain) NSString *name;
#property (nonatomic, retain) ThingTwo *thingTwo;
#property (nonatomic, retain) NSArray *values;
#property (nonatomic, retain) NSDictionary *dict;
#property int myInt;
#property float myFloat;
#property BOOL myBool;
#property (nonatomic, retain) NSNumber* someMoney;
#end
//
// ThingOne.m
// JasonStuff
//
// Created by Geoffrey Slinker on 12/28/15.
// Copyright © 2015 Slinkworks LLC. All rights reserved.
//
#import "ThingOne.h"
#implementation ThingOne
#synthesize name;
#synthesize thingTwo;
#synthesize values;
#synthesize dict;
#synthesize myInt;
#synthesize myFloat;
#synthesize myBool;
#synthesize someMoney;
- (instancetype)init
{
self = [super init];
thingTwo = [[ThingTwo alloc] init];
thingTwo.stuff = #"Thing Two Stuff";
thingTwo.someOtherStuff = #"Thing Two Other Stuff";
NSDateFormatter *dateFormater = [[NSDateFormatter alloc]init];
[dateFormater setDateFormat:#"yyyy-mm-dd"];
thingTwo.someDate = [dateFormater dateFromString:#"1963-10-07"];
values = [NSArray arrayWithObjects:#"Value1", #"Value2", #"Value3", nil];
dict = [NSDictionary dictionaryWithObjectsAndKeys:#"value1", #"key1", #"value2", #"key2", nil];
myInt = 5431;
myFloat = 123.456f;
myBool = YES;
someMoney = [NSNumber numberWithInt:503];
return self;
}
#end
//
// ThingTwo.h
// JasonStuff
//
// Created by Geoffrey Slinker on 12/28/15.
// Copyright © 2015 Slinkworks LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "GSObject.h"
#interface ThingTwo : GSObject
#property (nonatomic, retain) NSString *stuff;
#property (nonatomic, retain) NSString *someOtherStuff;
#property (nonatomic, retain) NSDate *someDate;
#property (nonatomic, retain) NSString *nullString;
#property (nonatomic, retain) NSDate *nullDate;
#end
//
// ThingTwo.m
// JasonStuff
//
// Created by Geoffrey Slinker on 12/28/15.
// Copyright © 2015 Slinkworks LLC. All rights reserved.
//
#import "ThingTwo.h"
#implementation ThingTwo
#synthesize stuff;
#synthesize someOtherStuff;
#synthesize someDate;
- (instancetype)init
{
self = [super init];
someDate = [NSDate date];
return self;
}
#end
Here is an example of the JSON output:
{
"values" : [
"Value1",
"Value2",
"Value3"
],
"myInt" : 5431,
"myFloat" : 123.456,
"myBool" : true,
"someMoney" : "$503.00",
"thingTwo" : {
"stuff" : "Thing Two Stuff",
"nullDate" : null,
"someDate" : "1963-01-07 07:10:00 +0000",
"nullString" : null,
"someOtherStuff" : "Thing Two Other Stuff"
},
"name" : "John Jones",
"dict" : {
"key1" : "value1",
"key2" : "value2"
}
}
have a look at https://github.com/icanzilb/JSONModel, from cocoapods
all (de)serialization is handled automatically for you, even complex structures of array of custom objects.
Been using it, been loving it...
CJSHWork as a class is defined in CJSHWork.h and CJSHWork.m. In CJSHWork.h I have:
#interface CJSHWork : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *url;
-(id) initWithName:(NSString *)name filename:(NSString *)title content:(NSString *)url;
#end
In CJSHWork.m I have:
- (id) initWithName:(NSString *)name title:(NSString *)title content:(NSString *)url
{
self = [super init];
if (self)
{
_name = name;
_title = title;
_url = url;
}
}
And I have, in CJSHDataController.m,
import "CJSHWork.h"
...
CJSHWork *work = [[CJSHWork alloc] initWithName:#"" title:allWorks[i][1] url:url];
This gets the error "No visible #interface for CJSHWork declares the selector initWithName title url".
What is going on here, and how can I fix it?
Your method name is initWithName:title:content: not initWithName:title:url:
Following a book tutorial and seem to run into a snag with the "isGameCenterAvailable" error.
Apparently it is undeclared. Everything else seems to work however so I just need to figure this part out.
Helloworldlayer .m init method
#import <GameKit/GameKit.h>
GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper]; gkHelper.delegate = self;
[gkHelper authenticateLocalPlayer];
Class gameKitLocalPlayerClass = NSClassFromString(#"GKLocalPlayer"); bool isLocalPlayerAvailable = (gameKitLocalPlayerClass != nil);
// Test if device is running iOS 4.1 or higher
NSString* reqSysVer = #"4.1";
NSString* currSysVer = [[UIDevice currentDevice] systemVersion]; bool isOSVer41 = ([currSysVer compare:reqSysVer
options:NSNumericSearch] != NSOrderedAscending);
isGameCenterAvailable = (isLocalPlayerAvailable && isOSVer41);
-(void) onLocalPlayerAuthenticationChanged {
[delegate onLocalPlayerAuthenticationChanged];
}
-(void) authenticateLocalPlayer {
GKLocalPlayer* localPlayer = [GKLocalPlayer localPlayer];
if (localPlayer.authenticated == NO) {
[localPlayer authenticateWithCompletionHandler: ^(NSError* error) {
[self setLastError:error]; }];
}
}
Gamekit.h
#import "cocos2d.h"
#import <GameKit/GameKit.h>
#protocol GameKitHelperProtocol
-(void) onLocalPlayerAuthenticationChanged; -(void) onFriendListReceived: (NSArray*)friends; -(void) onPlayerInfoReceived:(NSArray*)players; #end
#interface GameKitHelper : NSObject {
id<GameKitHelperProtocol> delegate; bool isGameCenterAvailable; NSError* lastError;
}
#property (nonatomic, retain) id<GameKitHelperProtocol> delegate;
#property (nonatomic, readonly) bool isGameCenterAvailable; #property (nonatomic, readonly) NSError* lastError;
+(GameKitHelper*) sharedGameKitHelper;
// Player authentication, info
-(void) authenticateLocalPlayer;
-(void) getLocalPlayerFriends;
-(void) getPlayerInfo:(NSArray*)players;
#end
helloworld layer.h
#import "GameKitHelper.h"
#interface helloworldlayer : CCLayer <GameKitHelperProtocol>
{
}
gamekithelper. h
#import "cocos2d.h"
#import <GameKit/GameKit.h>
#protocol GameKitHelperProtocol
-(void) onLocalPlayerAuthenticationChanged; -(void) onFriendListReceived:(NSArray*)friends; - (void) onPlayerInfoReceived:(NSArray*)players; #end
#interface GameKitHelper : NSObject {
id<GameKitHelperProtocol> delegate; bool isGameCenterAvailable; NSError* lastError;
}
#property (nonatomic, retain) id<GameKitHelperProtocol> delegate;
#property (nonatomic, readonly) bool isGameCenterAvailable; #property (nonatomic, readonly) NSError* lastError;
+(GameKitHelper*) sharedGameKitHelper;
// Player authentication, info
-(void) authenticateLocalPlayer;
-(void) getLocalPlayerFriends;
-(void) getPlayerInfo:(NSArray*)players;
#end
The problem is you never actually declare isGameCenterAvailable. To fix this, do this:
//HelloWorldLayer.h
#property (nonatomic) BOOL isGameCenterAvailable;
//HelloWorldLayer.m
#synthesize isGameCenterAvailable = _isGameCenterAvailable;
UPDATE:
To fix the delegate error, try this:
//HelloWorldLayer.h
#property (nonatomic, retain) id<GameKitHelperProtocol> delegate;
//HelloWorldLayer.m
#synthesize delegate;
Hope this helps!
I get "! Expected identifier or '('" next to the #import, as well as "Missing context for property implementation" next to the #synthesize directives for the namespace variable onward and the init method.
SoapService.h
#import "SoapDelegate.h"
#interface SoapService : NSObject
{
NSString* _serviceUrl;
NSString* _namespace;
NSString* _username;
NSString* _password;
NSDictionary* _headers;
BOOL _logging;
id<SoapDelegate> _defaultHandler;
}
#property (retain) NSString* serviceUrl;
#property (retain) NSString* namespace;
#property (retain) NSString* username;
#property (retain) NSString* password;
#property (retain) NSDictionary* headers;
#property BOOL logging;
#property (nonatomic, retain) id<SoapDelegate> defaultHandler;
- (id) initWithUrl: (NSString*) url; - (id) initWithUsername: (NSString*) serviceUsername andPassword: (NSString*) servicePassword;
#end
SoapService.m
#import "SoapService.h"
#implementation SoapService
#synthesize serviceUrl = _serviceUrl;
#synthesize namespace = _namespace;
#synthesize logging = _logging;
#synthesize headers = _headers;
#synthesize defaultHandler = _defaultHandler;
#synthesize username = _username;
#synthesize password = _password;
- (id) init {
if ((self = [super init])) {
self.serviceUrl = nil;
self.namespace = nil;
self.logging = NO;
self.headers = nil;
self.defaultHandler = nil;
self.username = nil;
self.password = nil;
}
return self;
}
- (id) initWithUrl: (NSString*) url {
if((self = [self init])) {
self.serviceUrl = url;
}
return self;
}
- (id) initWithUsername: (NSString*) serviceUsername andPassword: (NSString*) servicePassword {
if ((self = [self init])) {
self.username = serviceUsername;
self.password = servicePassword;
}
return self;
}
-(void)dealloc {
[_serviceUrl release];
[_namespace release];
[_username release];
[_password release];
[_headers release];
[_defaultHandler release];
[super dealloc];
}
#end
SoapDelegate.h
#import "SoapFault.h"
#protocol SoapDelegate <NSObject>
- (void) onload: (id) value;
#optional
- (void) onerror: (NSError*) error;
- (void) onfault: (SoapFault*) fault;
#end
I can't see anything wrong! I tried
changing the variable name from
namespace to namespacexx, but no
success.
SoapFault.h
#import "TouchXML.h"
#interface SoapFault : NSObject {
NSString* faultCode;
NSString* faultString;
NSString* faultActor;
NSString* detail;
BOOL hasFault;
}
#property (retain, nonatomic) NSString* faultCode;
#property (retain, nonatomic) NSString* faultString;
#property (retain, nonatomic) NSString* faultActor;
#property (retain, nonatomic) NSString* detail;
#property BOOL hasFault;
+ (SoapFault*) faultWithData: (NSMutableData*) data;
+ (SoapFault*) faultWithXMLDocument: (CXMLDocument*) document;
+ (SoapFault*) faultWithXMLElement: (CXMLNode*) element;
#end
TouchXML.h
#import "CXMLDocument.h"
#import "CXMLElement.h"
#import "CXMLNode.h"
#import "CXMLNode_XPathExtensions.h"
I can go further, but would like to
state that I am compiling with Xcode
4.0.2 and the previous version of the Xcode compiler did NOT raise these
semantic issues. This leads me to
believe that there is some syntax or
notation that has been deprecated.
CXMLDocument.h
#import "CXMLNode.h"
enum {
CXMLDocumentTidyHTML = 1 << 9
};
#class CXMLElement;
#interface CXMLDocument : CXMLNode {
NSMutableSet *nodePool;
}
- (id)initWithXMLString:(NSString *)inString options:(NSUInteger)inOptions error:(NSError **)outError;
- (id)initWithContentsOfURL:(NSURL *)inURL options:(NSUInteger)inOptions error:(NSError **)outError;
- (id)initWithData:(NSData *)inData options:(NSUInteger)inOptions error:(NSError **)outError;
//- (NSString *)characterEncoding;
//- (NSString *)version;
//- (BOOL)isStandalone;
//- (CXMLDocumentContentKind)documentContentKind;
//- (NSString *)MIMEType;
//- (CXMLDTD *)DTD;
- (CXMLElement *)rootElement;
//- (NSData *)XMLData;
//- (NSData *)XMLDataWithOptions:(NSUInteger)options;
//- (id)objectByApplyingXSLT:(NSData *)xslt arguments:(NSDictionary *)arguments error:(NSError **)error;
//- (id)objectByApplyingXSLTString:(NSString *)xslt arguments:(NSDictionary *)arguments error:(NSError **)error;
//- (id)objectByApplyingXSLTAtURL:(NSURL *)xsltURL arguments:(NSDictionary *)argument error:(NSError **)error;
//- (id)XMLStringWithOptions:(NSUInteger)options;
#end
CXMLNode.h
#import <Foundation/Foundation.h>
#include <libxml/tree.h>
typedef enum {
CXMLInvalidKind = 0,
CXMLElementKind = XML_ELEMENT_NODE,
CXMLAttributeKind = XML_ATTRIBUTE_NODE,
CXMLTextKind = XML_TEXT_NODE,
CXMLProcessingInstructionKind = XML_PI_NODE,
CXMLCommentKind = XML_COMMENT_NODE,
CXMLNotationDeclarationKind = XML_NOTATION_NODE,
CXMLDTDKind = XML_DTD_NODE,
CXMLElementDeclarationKind = XML_ELEMENT_DECL,
CXMLAttributeDeclarationKind = XML_ATTRIBUTE_DECL,
CXMLEntityDeclarationKind = XML_ENTITY_DECL,
CXMLNamespaceKind = XML_NAMESPACE_DECL,
} CXMLNodeKind;
#class CXMLDocument;
// NSXMLNode
#interface CXMLNode : NSObject {
xmlNodePtr _node;
}
- (CXMLNodeKind)kind;
- (NSString *)name;
- (NSString *)stringValue;
- (NSUInteger)index;
- (NSUInteger)level;
- (CXMLDocument *)rootDocument;
- (CXMLNode *)parent;
- (NSUInteger)childCount;
- (NSArray *)children;
- (CXMLNode *)childAtIndex:(NSUInteger)index;
- (CXMLNode *)previousSibling;
- (CXMLNode *)nextSibling;
//- (CXMLNode *)previousNode;
//- (CXMLNode *)nextNode;
//- (NSString *)XPath;
//- (NSString *)localName;
//- (NSString *)prefix;
//- (NSString *)URI;
//+ (NSString *)localNameForName:(NSString *)name;
//+ (NSString *)prefixForName:(NSString *)name;
//+ (CXMLNode *)predefinedNamespaceForPrefix:(NSString *)name;
- (NSString *)description;
- (NSString *)XMLString;
- (NSString *)XMLStringWithOptions:(NSUInteger)options;
//- (NSString *)canonicalXMLStringPreservingComments:(BOOL)comments;
- (NSArray *)nodesForXPath:(NSString *)xpath error:(NSError **)error;
- (NSString*)_XMLStringWithOptions:(NSUInteger)options appendingToString:(NSMutableString*)str;
#end
There's probably something wrong in SoapService.h since the error is showing it near the #import. At compile time, the preprocessor takes the text from this file and puts it at this point. Sometimes a syntax error in the .h isn't figured out until it gets back to the .m. Look near the end of SoapService.h
I think that namespace is a reserved word. Try to change it to something else.
How to access variables of other class? This is how I implemented it.
#interface Class1 :NSObject {
NSString *Data;
}
#property (nonatomic, retain) NSString *Data;
#implementation Class1
#synthesize Data;
someMethod{
self.Data = #"something";
}
and in Class2 :
#implementation Class2
someMethodOfClass2{
Class1 *c=[[Class1 alloc]init];
[c someMethod];
NSString *str=c.Data;
}
I get c.Data as null in Class2. Am I doing anything wrong here?
-----------myClass1--------------
#interface APIManager : NSObject {
NSString *Data;
}
#property (nonatomic, retain) NSString *Data;
-(void)getData;
#end
#implementation APIManager
#synthesize Data;
-(void)getData{
self.Data=#"response";
}
--------myClass2-------------
#interface Search : NSObject {
}
-(void)searchForItems:(NSString *)query;
#end
#implementation Search
-(void)searchForItems:(NSString *)query {
APIManager *apiManager=[[APIManager alloc]init];
[apiManager getData];
NSLog(#"%#",[apiManager Data]);
}
You should probably use self.Data = #"something" instead of self.Data = "something"
In Objective-C you have to use #"something" instead of "something". Also aren't you missing the variable declaration? In your #interface you should do something like NSString *Data.