Greg’s Online CS 193P Resources

April 25, 2009

Assignment 3 Code Snips

Filed under: cs 193p — gregorykaiser @ 2:50 am
Tags:

Here are my assignment 3 code snips. I used the IB to tie things together and I did not code object initializations as some did. My biggest time drain was forgetting to tie the PolygonView to controller in IB. From the Google group I see many others had this problem.

Look at the Google group to see how to add the extra credit parts as I did not do those here. I learned a lot by reading the group after I finished this. Good Luck!


--Controller.h
#import 
#import 
#import "PolygonShape.h"
#import "PolygonView.h"


@interface Controller : NSObject {
    IBOutlet UIButton *decreaseButton;
    IBOutlet UIButton *increaseButton;
    IBOutlet UILabel *numberOfSidesLabel;
	IBOutlet UILabel *nameLabel; 
	IBOutlet PolygonShape *polygon;
	IBOutlet PolygonView *view;		// 3 
}
- (IBAction)decrease;
- (IBAction)increase;
- (void)updateInterface;
@end
---Controller.m
#import "Controller.h"

@implementation Controller
//For 2a walkthrough
- (void)updateInterface {
	numberOfSidesLabel.text = [ NSString stringWithFormat:@"%d", polygon.numberOfSides];
	nameLabel.text = [NSString stringWithFormat:@"%@", polygon.name];
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];		//3
	[prefs setInteger:polygon.numberOfSides forKey:@"integerKey"];		//3
	if (polygon.numberOfSides == polygon.minimumNumberOfSides) {
		decreaseButton.enabled = NO;
	} else {
		decreaseButton.enabled = YES ;
	}
	if (polygon.numberOfSides == polygon.maximumNumberOfSides) {
		increaseButton.enabled = NO ;
	} else {
		increaseButton.enabled = YES ;
	}
	[view setNeedsDisplay];  //view was null, until hooked up in ib
}

- (void)awakeFromNib {
	//configure polygon here
	// NSLog(@"Entering awakeFromNib");
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];		//3
	NSInteger savedSides = [prefs integerForKey:@"integerKey"];			//3
	NSLog(@"SavedSides: %d",savedSides);
	if (savedSides) {	//3
		polygon.numberOfSides = (int)savedSides ;						//3
	} else {
		polygon.numberOfSides = numberOfSidesLabel.text.integerValue;	//3
	}																	//3
	polygon.maximumNumberOfSides = 12;
	polygon.minimumNumberOfSides = 3;
	NSLog(@"awakeFromNib in Controller: My Polygon:%@   Min:%d  Max:%d", [polygon name], polygon.minimumNumberOfSides, polygon.maximumNumberOfSides);
	self.updateInterface;
}

- (IBAction)decrease {
	NSLog(@"Entering Controller.Decrease");  
	int sides = polygon.numberOfSides;
	if (sides > polygon.minimumNumberOfSides) {
		polygon.numberOfSides = sides - 1;
	} else {
		NSLog(@"Already at minimum");
	}
	self.updateInterface;
}

- (IBAction)increase {
	NSLog(@"Entering Controller.Increase");      
	int sides = polygon.numberOfSides;
	if (sides < polygon.maximumNumberOfSides) {
		polygon.numberOfSides = sides + 1;
	} else {
		NSLog(@"Already at maximum");
	}
	self.updateInterface;
}

@end
---PolygonShape.h
//
//  PolygonShape.h
//  HelloPoly2
//

#import 


@interface PolygonShape : NSObject {
	int numberOfSides;
	int minimumNumberOfSides;
	int maximumNumberOfSides;
}

@property (readwrite) int numberOfSides;
@property (readwrite) int minimumNumberOfSides;
@property (readwrite) int maximumNumberOfSides;
@property (readonly) float angleInDegrees;
@property (readonly) float angleInRadians;
@property (readonly) NSString * name;
@property (readonly) NSString * description;

- (id)initWithNumberOfSides:(int)sides minimumNumberOfSides:(int)min maximumNumberOfSides:(int)max;
- (id)init;
- (void)dealloc;

@end
---PolygonShape.m
//
//  PolygonShape.m
//  HelloPoly2
//
//

#import "PolygonShape.h"


@implementation PolygonShape
- (id)initWithNumberOfSides:(int)sides minimumNumberOfSides:(int)min maximumNumberOfSides:(int)max; {

	[self setMinimumNumberOfSides:(int)min];
	[self setMaximumNumberOfSides:(int)max];
	[self setNumberOfSides:(int)sides];
	return self;
}

- (id)init {
	return [self initWithNumberOfSides:5 minimumNumberOfSides:3 maximumNumberOfSides:12];
}	
	
@synthesize numberOfSides;
- (void)setNumberOfSides:(int)value {
	if (value = minimumNumberOfSides) {
		numberOfSides = value;
	} else {
		NSLog(@" In setNumberOfSides - ERROR - sides:%d Is not in the valid range: %d to %d . So it is still %d", value, minimumNumberOfSides, maximumNumberOfSides, numberOfSides);
	}
}

@synthesize minimumNumberOfSides;
// add maxcheck later if needed
- (void)setMinimumNumberOfSides:(int)value {
	if (value  (int)12) {
		maximumNumberOfSides = (int)12;
	} else {
		maximumNumberOfSides = value;
	}
	//NSLog(@" In maximunNumberOfSides value: %d  Returns: %d ", value, maximumNumberOfSides);
}

- (float) angleInDegrees; {
	return (float)((180.0 * (numberOfSides - 2)) / numberOfSides);
}

- (float) angleInRadians; {
	return (float)[self angleInDegrees] * ((3.1415926 * 2.0)/360.0);
}

- (NSString *)name; {
	NSArray *xlate = [NSArray arrayWithObjects:@"Bad0", @"Bad1", @"Bad2", @"Triangle", @"Square", @"Pentagon", @"Hexagon",
	@"Heptagon", @"Octagon", @"Nonagon", @"Decagone", @"Hendecagon", @"Dodecagon", nil]; 
	//NSString *firstColor = [colors objectForKey:@”Color 1”];
	
	return  (NSString *)[xlate objectAtIndex:numberOfSides];
}

- (NSString *)description; {
	NSLog(@"Hello I am a %d-sided polygone (aka a %@) with angles of %f degrees (%f radians)", self.numberOfSides, 
		  [self name], [self angleInDegrees], [self angleInRadians]);
	return  (NSString *)[self name];
}

- (void)dealloc {
	NSLog(@"DEALLOC called on polyShape");
	[super dealloc];
}	

@end

---PolygonView.h
#import 
#import 
#import "PolygonShape.h"

@interface PolygonView : UIView {
	
	IBOutlet PolygonShape *polygon;
}
//@property (readonly) PolygonView *view;

- (void)drawRect:(CGRect)rect;

@end


---PolygonView.m
#import "PolygonView.h"

@implementation PolygonView
+ (NSArray *)pointsForPolygonInRect:(CGRect)rect numberOfSides:(int)numberOfSides { 
	CGPoint center = CGPointMake(rect.size.width / 2.0, rect.size.height / 2.0); 
	if (numberOfSides % 2 != 0) {		// if added to better center polygons
		center.y = center.y * (1.0 + .1 * ((12.0 - (float)numberOfSides) / 12.0));
	}
	float radius = 0.8 * center.x;   // was 0.9
	NSMutableArray *result = [NSMutableArray array]; 
	float angle = (2.0 * M_PI) / numberOfSides; 
	float exteriorAngle = M_PI - angle; 
	float rotationDelta = angle - (0.5 * exteriorAngle); 
	// for loop was mangled prior to 5/21 - see comment in blog
	for (int currentAngle = 0; currentAngle < numberOfSides; currentAngle++) { 
		float newAngle = (angle * currentAngle) - rotationDelta; 
		float curX = cos(newAngle) * radius; 
		float curY = sin(newAngle) * radius; 
		&#91;result addObject:&#91;NSValue valueWithCGPoint:CGPointMake(center.x + curX, 
																center.y + curY)&#93;&#93;; 
	} 
	
	return result; 
} 

- (void)drawRect:(CGRect)rect {
	NSLog(@"-->drawrect");
	CGContextRef context = UIGraphicsGetCurrentContext();
	CGRect bounds = [self bounds]; 
	[[UIColor darkGrayColor] set]; 
	UIRectFill (bounds); 
	[[UIColor lightGrayColor] setFill]; 
	[[UIColor blueColor] setStroke]; 
	CGContextDrawPath (context, kCGPathFillStroke); 
	// 3
	NSArray *pts;
	int i;
	NSValue *theValue;
	CGPoint thePoint;

	pts = [PolygonView pointsForPolygonInRect:bounds numberOfSides:polygon.numberOfSides];  // was self then + for class
	CGContextBeginPath (context); 
	theValue = [pts objectAtIndex:(NSInteger)0];
	thePoint = [theValue CGPointValue]; 
	CGContextMoveToPoint (context, thePoint.x, thePoint.y); 
	for (i = 1; i &lt; polygon.numberOfSides; i++) {
		theValue = [pts objectAtIndex:(NSInteger)i];
		thePoint = [theValue CGPointValue]; 
		CGContextAddLineToPoint (context, thePoint.x, thePoint.y); 
	}
	theValue = [pts objectAtIndex:(NSInteger)0];
	thePoint = [theValue CGPointValue]; 
	CGContextAddLineToPoint(context, thePoint.x, thePoint.y); 
	
	CGContextDrawPath (context, kCGPathFillStroke);
	return;
}
@end

Advertisements

10 Comments »

  1. “…forgetting to tie the PolygonView to controller in IB…”.

    This is where I’m stuck, but I’m unclear from the various group discussions how to solve it. If you wouldn’t mind, please could you post or point to the relevant group posting as to how you solved this?

    Many thanks

    Comment by jfconno — April 30, 2009 @ 11:50 am | Reply

  2. is there something wrong on PolygonView.m line 16?

    Comment by Rio — May 21, 2009 @ 12:06 pm | Reply

    • Yes you are right. From the middle of the for statement to the middle of the next member got dropped. I fixed it. Thanks

      Comment by gregorykaiser — May 21, 2009 @ 1:46 pm | Reply

  3. hello greg,

    I am not familiar with the MVC design pattern, and I was stocked wondering how can I pass the integer value of Model(numberOfSides) to View (polyView) through controller. I don’t know If what u did is correct to let the view object has a ivar as polygon. Does it violates the MVC pattern? How can I do to follow the rule?

    Comment by Rio — May 21, 2009 @ 12:15 pm | Reply

    • Evan said in the lecture not to worry about MVC in this assignment. Look for the post later on about passing data (Person) between classes where it is done right (I think) thanks for your comments.

      Greg

      Comment by gregorykaiser — May 21, 2009 @ 1:48 pm | Reply

  4. Thanks so much for “forgetting to tie the PolygonView to controller in IB”.
    I had compared my code so many times with yours and others, but what was missing were the links!

    Comment by Christina — June 23, 2009 @ 4:17 am | Reply

    • I am glad it helped.

      Comment by gregorykaiser — June 23, 2009 @ 11:04 am | Reply

  5. I don’t think that code is perfect, far from it…. It looks messy and written by someone who’s very new to Obj-C.

    Comment by Azhen — June 23, 2009 @ 9:56 am | Reply

    • You are right of course. I started learning with this class. My goal here was trying to help people along when the class was going. I was spending a lot of time finding information to get started and hoped these snips would help others. They are not ment to be textbook examples of great obj-c. I still think “Beginning iPhone Development” is a great book to learn this stuff from.

      Greg

      Comment by gregorykaiser — June 23, 2009 @ 11:08 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: