-2

The variables bounds, width and height are at present local variables. I cannot access them from other classes or even access them from another method.

How can I make these variables available to the whole instance? I have tried placing them within the .h file and renaming them to CGFloats to no avail.

#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
Declan McKenna
  • 4,321
  • 6
  • 54
  • 72

4 Answers4

1

bounds, width and height are local variables that exist only in the context of the drawRect method.

Why don't you use:

CGRect bounds = [self bounds];
float width = bounds.size.width;
float height = bounds.size.height;

in other methods?

mouviciel
  • 66,855
  • 13
  • 106
  • 140
  • lol dunno why that didn't occur to me. Would retyping this into other methods not be worse practise than making the variables more accessible? As I see no reason to keep them as local variables when they describe an instance's attribute. – Declan McKenna Nov 07 '11 at 17:06
1

You can use properties to make variables accessible to other objects.

In your interface add something like this:

@property (nonatomic, retain) NSString *myString;

and then add

@synthesize mystring;

to your implementation.

Two methods will be created to get the property and to change it.

[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";

You can change the value of a property within a class using [self setMystring:@"new value"] or if you have the same variable already declared in the interface and then create a property from it you can keep using your variables within the class the way you are .

There's more info on properties in the developer docs: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1

Anthony Mattox
  • 7,048
  • 6
  • 43
  • 59
0

Make them member variables or properties and write accessors or synthesize them. See the Objective-C language reference.

tobiasbayer
  • 10,269
  • 4
  • 46
  • 64
0

Use getters setters or generate it with a

@property(nonatomic) CGFloat width;

@synthesize width;
Mathieu Hausherr
  • 3,485
  • 23
  • 30