1

I'm a beginner of iPhone app development. I'm working on an app that communicate with an external hardware using the dock to RS232 cable I got from RedPark. I wrote the most code myself, but I am still confused about several things.

I want to have several views in my app and each view has a button, that when pressing the button, it sends different command to the hardware. So I create a NSObject to take care of the sending part. My question is how to properly call the send method of that NSObject. Communication.h

@interface Communication : NSObject<RscMgrDelegate>
{
    RscMgr * rscMgr;
}
@property (nonatomic,retain)RscMgr *rscMgr;
- (void)sendRequest;
@end

Communication.m

@synthesize rscMgr=_rscMgr;
- (void)sendRequest{
if (!_rscMgr) {
    rscMgr = [[RscMgr alloc]init];
    [rscMgr setDelegate:self];
}

UInt8 sendData[4]={0x8E,0x8E,0x05,0x80};
[rscMgr write:sendData Length:4];
NSLog(@"sending request");

}

BTW, RscMgr is a NSObject provided by RedPark that uses their library. Singletest.m

- (Communication *)communication{
if(!_communication){
    _communication=[[Communication alloc]init];
}
return _communication;
}
- (IBAction)sendData:(id)sender{
[self.communication sendRequest];
NSLog(@"Send Data");
}

What happens now is the first time I press the button, it did send a command, but not afterwards. I think I just made a stupid mistake since I'm still learning it. Please let me know.
Thank you.

user1491987
  • 751
  • 1
  • 14
  • 34

1 Answers1

0

I would turn Communication into a singleton class which is responsible for instantiating and holding the pointer to RscMgr, then you can do something like this

Communication* comm = [Communication sharedInstance];
[comm sendRequest];

Your sendRequest would then be responsible for calling whatever methods are needed on RscMgr. Note, sharedInstance you have to write, if you need an example of how to write a singleton class in Objective C let me know.

Joe
  • 2,352
  • 20
  • 38
  • I provided more code to explain my question. Can you give an example of singleton class? Thank you. – user1491987 Jul 05 '12 at 21:56
  • Yes, this evening I'll provide an example - still at the office right now :-) – Joe Jul 05 '12 at 22:08
  • Thanks a lot. BTW, can you tell me if I did anything wrong in my code? – user1491987 Jul 05 '12 at 22:45
  • 1
    [This is a good thread on Obj-C singleton](http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like) – SkylarSch Jul 05 '12 at 23:34
  • See Skylar's link above on singletons, much preferred to reference that than rewrite the book. Re: your code, look at your sendRequest method - there's no reason to put your "if RscMgr isn't created, create it" code there, do all that setup in your Communication construction. – Joe Jul 06 '12 at 00:04