【发布时间】:2012-06-03 22:29:20
【问题描述】:
我很难理解何时需要创建类方法。根据我的阅读,它们对于创建新对象很重要,但我不明白如何。下面的类创建一个简单的黑色矩形。谁能告诉我如何合并一个类方法来做一些我不能用实例方法做的事情?
形状.h
#import <UIKit/UIKit.h>
@interface Shape : UIView;
- (id) initWithX: (int)xVal andY: (int)yVal;
@end
形状.m
#import "Shape.h"
@implementation Shape
- (id) initWithX:(int )xVal andY:(int)yVal {
self = [super init];
UIView *shape = [[UIView alloc] initWithFrame:CGRectMake(xVal, yVal, 10, 10)];
shape.backgroundColor = [UIColor blackColor];
[self addSubview:shape];
return self;
}
@end
【问题讨论】:
-
你注意到
alloc是一个类方法了吗?一定是因为调用时没有对象。
标签: objective-c ios5 xcode4