Reputation: 3
I'm working on this assignment I found online (Intermediate App Development Using iOS). I'm stuck on part c and d, don't know exactly what its asking me to do.
I know how to print int (%i
) and object (%@
), but %@
print all data? Any help or suggestion will be appreciated.
Part 6
a) Implement class A
with properties a1
, a2
, and a3
(int
, string
, int
).
b) New objects are automatically initialized to 1
, "hello"
, 1
c) Also provide initializer to any data and constructor (called without alloc
) to do the same.
d) Make sure %@
object of A
will print all data.
Here is what I have done so far:
// classA.h
#import <Foundation/Foundation.h>
@interface ClassA : NSObject
// Part 6a
@property int a1;
@property NSString *a2;
@property int a3;
-(ClassA *) initWithA1: (int) x andA2: (NSString *) s andA3: (int) y;
@end
//classA.m
#import "ClassA.h"
@implementation ClassA
-(ClassA *) initWithA1:(int)x andA2:(NSString *)s andA3:(int)y {
self = [super init];
if (self) {
self.a1 = x;
self.a2 = s;
self.a3 = y;
}
return self;
}
// part 6b
-(ClassA *) init {
if (self = [super init]) {
self.a1 = 0;
self.a2 =@"hello";
self.a3 = 0;
}
return self;
}
@end
Upvotes: 0
Views: 118
Reputation: 7935
As @orbitor wrote, your class should have one designated initialiser.
So, your
init
method should probably read something like:
- (id) init
{
return [self initWithA1:1 andA2:@"hello" andA3:1];
}
In order to print all object you should implement custom description
method:
- (NSString *) description
{
return [NSString stringWithFormat:@"a1 = %d, a2 = %@, a3 = %d", self.a1, self.a2, self.a3];;
}
According to c:
Class method new
just calls alloc
and init
methods so you should only make sure that you wrote properly all initialisers.
Upvotes: 0
Reputation: 93
In reference to part "b" of your question:
As a general rule, only 1 initializer should be doing the "real" work. This is often referred to as the designated initializer. So, your init
method should probably read something like:
- (id) init
{
return [self initWithA1:1 andA2:@"hello" andA3:1];
}
Upvotes: 1