I try to understand how to work simple init funcion and I don’t know where I have made a mistake. Can somebody assist?
Rectangle.h
@interface Rectangle : NSObject
{
int width;
int height;
}
-(id)initObject;
@end
Rectangle.m
@implementation Rectangle
-(id)initObject{
if (self = [super init]) {
height = 5;
width = 7;
}
return self;
}
@end
And in ViewController.h i import Rectangle.h, declare *rect object and in .m i execute(? run?) initObject.
ViewController.h
#import <UIKit/UIKit.h>
#import "Rectangle.h"
@interface ViewController : UIViewController
{
Rectangle *rect;
}
@end
ViewController.m
-(void)viewDidLoad
{
rect = [[Rectangle alloc] initObject];
NSLog(@"%@", rect);
[super viewDidLoad];
}
initObject return me:
2011-11-21 09:43:02.625 initializers[43693:f803] <Rectangle: 0x6ab1660>
The only problem with your code that I can see is you called your initializer
-initObjectfor no good reason. It’s not taking any parameters at all, so you really should just call it-initlike every other parameterless initializer in the system.As for the log output, I imagine your confusion lies in the fact that it says
<Rectangle: 0x6ab1660>. This is perfectly normal. The default implementation of-description(the method that returns this output) is the name of the class of the object followed by the object’s address. In other words,-[NSObject description]is likely to be implemented something like the following:This means that instance variables of your object are not going to be printed. A number of built-in classes do print their instance variables when logged, but this was implemented specifically for that class and is not a generic mechanism. If you want to verify that your
Rectangleobject is correct, you could implement-descriptionlike so: