【发布时间】:2012-01-02 19:16:52
【问题描述】:
我试图了解如何使用简单的 init 函数,但我不知道我在哪里犯了错误。有人可以帮忙吗?
矩形.h
@interface Rectangle : NSObject
{
int width;
int height;
}
-(id)initObject;
@end
矩形.m
@implementation Rectangle
-(id)initObject{
if (self = [super init]) {
height = 5;
width = 7;
}
return self;
}
@end
我在 ViewController.h 中导入 Rectangle.h,声明 *rect 对象并在 .m 中执行(?运行?)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 返回我:
2011-11-21 09:43:02.625 initializers[43693:f803] <Rectangle: 0x6ab1660>
【问题讨论】:
-
为什么是“if (self = [super init]) {?”
-
没有问题,看起来不错。如果你想看
height和width写NSLog(@"%d, %d", rect.height, rect.width); -
我在许多示例中看到它只是看起来像。我还看到:self = [super init];如果(自我){...
-
@Brogrammer:经典的初始化风格使用
if ((self = [super init])) { ... }。这是 Cocoa 多年来一直使用的风格。最近有self = [super init]; if (self) { ... }的趋势,不过这个在功能上是一样的,虽然我个人认为是浪费一行。
标签: objective-c class import initialization