Reputation: 31
We have to convert our C# code to Objective-C code and i was having a hard time figuring out how to create one constructor with no arguments while the other with 2 arguments. This is the C# code that I am trying to convert:
namespace Account
{
class Program
{
public class Account
{
private double balance;
private int accountNumber;
public Account()
{
balance = 0;
accountNumber = 999;
}
public Account(int accNum, double bal)
{
balance = bal;
accountNumber = accNum;
}
}
}
}
And this is what I have so far for the Objective C not sure if it is even correct or not
@interface classname : Account
{
@private double balance;
@private int accountNumber;
@public Account()
}
Open to any help i can get thank you very much, Danny
Upvotes: 3
Views: 188
Reputation: 104698
you simply provide two initializers, which takes the general form:
@interface MONAccount : NSObject
@private
double balance;
int accountNumber;
}
/* declare default initializer */
- (id)init;
/* declare parameterized initializer */
- (id)initWithAccountNumber:(int)inAccountNumber balance:(int)inBalance;
@end
@implementation MONAccount
- (id)init
{
self = [super init];
/* objc object allocations are zeroed. the default may suffice. */
if (nil != self) {
balance = 0;
accountNumber = 999;
}
return self;
}
- (id)initWithAccountNumber:(int)inAccountNumber balance:(int)inBalance
{
self = [super init];
if (nil != self) {
balance = inBalance;
accountNumber = inAccountNumber;
}
return self;
}
@end
Upvotes: 3
Reputation: 9392
Objective C is a bit different from other languages. It has a weirder syntax compared to other languages. Though from what I've seen, it appears that you haven't learnt much about objective-c yet. I would recommend you look at apple's documentation or get a book to actually learn about how the objective-c syntax works. It shouldn't take too long to learn the syntax, but here's how you should do it.
@interface NSObject : Account
{
@private
double balance;
int accountNumber;
}
-(void)account; //No Arguements
-(void)account:(int)accNum withBalance:(double)bal; //2 Arguements
@implementation Program
-(void)account
{
balance = 0;
accountNumber = 999;
}
-(void)account:(int)accNum withBalance:(double)bal
{
balance = bal;
accountNumber = accNum;
}
Upvotes: 0