Iphone 如何使其他类可以访问我的变量?
目前,边界、宽度和高度等变量都是局部变量。我无法从其他类访问它们,甚至无法从其他方法访问它们 如何使这些变量可用于整个实例?我曾尝试将它们放在.h文件中,并将它们重命名为cgloats,但没有任何效果Iphone 如何使其他类可以访问我的变量?,iphone,objective-c,xcode,local-variables,Iphone,Objective C,Xcode,Local Variables,目前,边界、宽度和高度等变量都是局部变量。我无法从其他类访问它们,甚至无法从其他方法访问它们 如何使这些变量可用于整个实例?我曾尝试将它们放在.h文件中,并将它们重命名为cgloats,但没有任何效果 #import "TicTacToeBoard.h" @implementation TicTacToeBoard - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self)
#import "TicTacToeBoard.h"
@implementation TicTacToeBoard
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGRect bounds = [self bounds];
float width = bounds.size.width;
float height = bounds.size.height;
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 0.3, 0.3, 0.3, 1);
CGContextSetLineWidth(ctx, 5);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextMoveToPoint(ctx, width/3, height * 0.95);
CGContextAddLineToPoint(ctx, width/3, height * 0.05);
CGContextStrokePath(ctx);
}
@end
使它们成为成员变量或属性,并编写访问器或综合它们。
.使用getters setter或使用
@property(nonatomic) CGFloat width;
@synthesize width;
边界、宽度和高度是仅存在于drawRect方法上下文中的局部变量 你为什么不使用:
CGRect bounds = [self bounds];
float width = bounds.size.width;
float height = bounds.size.height;
在其他方法中?可以使用属性使其他对象可以访问变量 在界面中添加如下内容:
@property (nonatomic, retain) NSString *myString;
然后加上
@synthesize mystring;
为您的实现
将创建两个方法来获取和更改属性
[myObject myString]; // returns the property
[myObject setMyString:@"new string"]; // changes the property
// alternately, you can write it this way
myObject.myString;
myObject.mystring = @"new string";
您可以使用[self-setMystring:@“new-value”]
更改类中属性的值,或者如果您在接口中已声明了相同的变量,然后从该变量创建属性,则您可以继续使用类中的变量
开发者文档中有更多关于属性的信息:lol dunno为什么我没有想到这一点。将其重新输入其他方法是否比使变量更容易访问更糟糕?正如我所见,当它们描述实例的属性时,没有理由将它们保留为局部变量。