SlideShare a Scribd company logo
CS193P                                                                            Assignment 2A
Winter 2010                                                                    Cannistraro/Shaffer

                      Assignment 2A - WhatATool (Part II)
Due Date
This assignment is due by 11:59 PM, January 20.

 Assignment
Now that we have some Objective-C experience under our belt, we’ll dive into the world of
custom classes and more advanced Objective-C language topics. You will define and use a new
custom class, and learn about Objective-C categories.

We will use the same WhatATool project from last week as our starting point. A few more
sections will be added to the existing structure.

The basic layout of your program should look something like this:

#import <Foundation/Foundation.h>

// sample function for one section, use a similar function per section
void PrintPathInfo() {
	      // Code from path info section here
}

int main (int argc, const char * argv[]) {
    NSAutoreleasepool * pool = [[NSAutoreleasePool alloc] init];

	    PrintPathInfo();                  //   Section   1
	    PrintProcessInfo();               //   Section   2
	    PrintBookmarkInfo();              //   Section   3
	    PrintIntrospectionInfo();         //   Section   4
	    PrintPolygonInfo();               //   Section   6 (No function for section 5)

    [pool release];
    return 0;
}




Testing
In most assignments testing of the resulting application is the primary objective. In this case,
testing/grading will be done both on the output of the tool, but also on the code of each
section.

We will be looking at the following:
1. Your project should build without errors or warnings.
2. Your project should run without crashing.
3. Each section of the assignment describes a number of log messages that should be printed.
   These should print.
4. Each section of the assignment describes certain classes and methodology to be used to
   generate those log messages – the code generating those messages should follow the
   described methodology, and not be simply hard-coded log messages.

To help make the output of your program more readable, it would be helpful to put some kind
of header or separator between each of the sections.



                                            Page 1 of 4
CS193P                                                                            Assignment 2A
Winter 2010                                                                    Cannistraro/Shaffer


Assignment Walkthrough


Section 5: Creating a new class
Create a PolygonShape class. To create the files for the new class in Xcode:

1. Choose File > New File…
2. In the Cocoa section under Mac OS X, select the ‘Objective-C class’ template
3. Name the file PolygonShape.m – Be certain the checkbox to create a header file is also
   checked




Note that your new class inherits from NSObject by default, which happens to be what we want.

Now that we’ve got a class, we need to give it some attributes. Objective-C 2.0 introduced a
new mechanism for specifying and accessing attributes of an object. Classes can define
“properties” which can be accessed by users of the class. While properties usually allow
developers to avoid having to write boilerplate code for setting and getting attributes in their
classes, they also allow classes to express how an attribute can be used or what memory
management policies should be applied to a particular attribute. For example, a property can
be defined to be read-only or that an when an object property is set how the ownership of that
object should be handled.

In this section you will add some properties to your PolygonShape class.

1. Add the following properties to your PolygonShape class

    •  numberOfSides – an int value
    •  minimumNumberOfSides – an int value
    • maximumNumberOfSides – an int value
    • angleInDegrees – a float value, readonly
    •  angleInRadians – a float value, readonly
    •  name – an NSString object, readonly

2. The numberOfSides, minimumNumberOfSides and maximumNumberOfSides properties
   should all be backed by instance variables of the appropriate type. These properties should
   all be synthesized. When a property is “synthesized” the compiler will generate accessor
   methods for the properties according to the attributes you specify in the @property
   declaration. For example, if you specified a property as “readonly” then the compiler will

                                           Page 2 of 4
CS193P                                                                          Assignment 2A
Winter 2010                                                                  Cannistraro/Shaffer

    only generate a getter method but not a setter method.

3. Implement setter methods for each of the number of sides properties and enforce the
   following constraints:

    •  numberOfSides – between the minimum and maximum number of sides
    •  minimumNumberOfSides – greater than 2
    • maximumNumberOfSides – less than or equal to 12

    Attempts to set one of these properties outside of the constraints should fail and log an
    error message. For example, if you have a polygon that is configured with a
    maximumNumberOfSides set to 5 and you attempt to set the numberOfSides property to 9
    you should log a message saying something like:

        Invalid number of sides: 9 is greater than the maximum of 5 allowed

4. Implement a custom initializer method that takes the number of sides for the polygon:

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

    Your initializer should set the minimum and maximum number of sides first (to establish the
    constraints) and then set the number of sides to the value passed in.

5. Implement a custom init method (overriding the version implemented in NSObject) which
   calls your custom initializer with default values. For example, your generic -[PolygonShape
   init] method might create a 5 sided polygon with min of 3 sides and max of 10.

6. The angleInDegrees and angleInRadians properties should not be stored in an instance
   variable since they are all properties derived by the numberOfSides. These properties do
   not need to be synthesized and you should implement methods for each of them which
   return the appropriate values. We’re being boring and using regular polygons so the angles
   are all the same.

7. Similarly, the name property should also not be synthesized (nor stored in an instance
   variable) and you should implement a method for it. The name of the polygon should be a
   descriptive name for the number of sides. For example, if a polygon has 3 sides it is a
   “Triangle” A 4-sided polygon is a “Square”
              .                             .

8. Give your PolygonShape class a -description method. Example output from this method:

        Hello I am a 4-sided polygon (aka a Square) with angles of 90 degrees
    (1.570796 radians).

9. In order to verify your memory management techniques, implement a dealloc method and
   include an NSLog statement indicating that dealloc is being called.


Section Hints:
   • You can find a list of names for polygons on the web. Wikipedia has a good one.
    • The formula for computing the internal angle of a regular polygon in degrees is (180 *
      (numberOfSides - 2) / numberOfSides).
    • Remember your trigonometry: 360° is equal to 2π.

                                          Page 3 of 4
CS193P                                                                            Assignment 2A
Winter 2010                                                                    Cannistraro/Shaffer

     • You can use the preprocessor value M_PI for π.

Section 6: Using the PolygonShape class
Write a C function (e.g. PrintPolygonInfo) called by main() that uses your newly created
PolygonShape class.

You will have to add an import statement to the WhatATool.m file:
         #import "PolygonShape.h"

IMPORTANT: In this section, you are expected to use +alloc and –init methods to create the
polygons and the array that they are put into. You must practice correct memory
management techniques of releasing the polygon objects when you are done with them.

1.   Create a mutable array (using alloc/init).

2. Create 3 (or more) PolygonShape instances with the following values:

       Min number of sides          Max number of sides         Number of sides

                  3                               7                      4

                  5                               9                      6

                  9                           12                        12

       When allocating your polygons, use a mixture of vanilla alloc/init then set the properties
       along with using your custom initializer method that takes all of the properties in the
       initializer method.

3. As you create each polygon, add them to the array of polygons and emit a log with the
     polygon’s description. There should be at least 3 descriptions logged.

4. Test the constraints on your polygons. Iterate over the array of polygons and attempt to set
     their numberOfSides properties to 10. This should generate two logs indicating that the
     number of sides doesn’t fall within the constraints (for the first two polygons in the table
     above).

5. Verify that your polygon objects are being deallocated correctly. If you have followed the
     rules correctly with regard to memory management you should see 3 logs from the
     dealloc method of your polygons. If you do not see these logs, review your alloc/init and
     release calls to make sure they are correctly balanced for your polygon objects as well as
     the array you are putting them into. Remember, alloc/init and release work like malloc
     and free in C.




                                             Page 4 of 4

More Related Content

RTF
Imp_Points_Scala
PDF
MA3696 Lecture 9
PPTX
PPT
Lecture 7
PPTX
Advanced Python : Decorators
PDF
C programming day#2.
PPT
Bad Smell in Codes - Part 1
PPT
C++ Memory Management
Imp_Points_Scala
MA3696 Lecture 9
Lecture 7
Advanced Python : Decorators
C programming day#2.
Bad Smell in Codes - Part 1
C++ Memory Management

What's hot (13)

PDF
C sharp chap6
PDF
C sharp chap5
PDF
C,c++ interview q&a
PDF
C sharp chap4
PPTX
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
PPTX
Pointer and polymorphism
PPT
Templates exception handling
KEY
Domänenspezifische Sprachen mit Xtext
PDF
Generic Programming
PPTX
Basic iOS Training with SWIFT - Part 2
PPTX
Pointers,virtual functions and polymorphism cpp
PPT
Pointers
C sharp chap6
C sharp chap5
C,c++ interview q&a
C sharp chap4
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Pointer and polymorphism
Templates exception handling
Domänenspezifische Sprachen mit Xtext
Generic Programming
Basic iOS Training with SWIFT - Part 2
Pointers,virtual functions and polymorphism cpp
Pointers
Ad

Viewers also liked (15)

PDF
Paparazzi2
PDF
08 Table Views
PDF
06 View Controllers
DOC
New Study Of Gita Nov 8 Dr Shriniwas J Kashalikar
PDF
01 Introduction
PDF
04 Model View Controller
PPT
PDF
07 Navigation Tab Bar Controllers
PDF
مهارات التعامل مع الغير
PPT
Appleipad 100205071918 Phpapp02
PDF
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
PDF
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
PDF
Handout 00 0
PDF
الشخصية العبقرية
PDF
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
Paparazzi2
08 Table Views
06 View Controllers
New Study Of Gita Nov 8 Dr Shriniwas J Kashalikar
01 Introduction
04 Model View Controller
07 Navigation Tab Bar Controllers
مهارات التعامل مع الغير
Appleipad 100205071918 Phpapp02
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
Handout 00 0
الشخصية العبقرية
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
Ad

Similar to Assignment2 A (20)

PDF
Assignment3
PPTX
iOS Session-2
ZIP
PDF
iOS Programming Intro
PDF
Louis Loizides iOS Programming Introduction
ZIP
PDF
201005 accelerometer and core Location
PDF
FI MUNI 2012 - iOS Basics
PDF
Iphone course 1
PDF
My Adventures In Objective-C (A Rubyists Perspective)
PDF
Assignment1 B 0
PDF
Никита Корчагин - Programming Apple iOS with Objective-C
PDF
MFF UK - Introduction to iOS
PPT
Objective c
PPTX
Presentation 1st
PDF
iPhone Seminar Part 2
PDF
Programming with Objective-C
PPT
Objective-C for iOS Application Development
PDF
Introduction to Objective - C
PDF
Lecture 03
Assignment3
iOS Session-2
iOS Programming Intro
Louis Loizides iOS Programming Introduction
201005 accelerometer and core Location
FI MUNI 2012 - iOS Basics
Iphone course 1
My Adventures In Objective-C (A Rubyists Perspective)
Assignment1 B 0
Никита Корчагин - Programming Apple iOS with Objective-C
MFF UK - Introduction to iOS
Objective c
Presentation 1st
iPhone Seminar Part 2
Programming with Objective-C
Objective-C for iOS Application Development
Introduction to Objective - C
Lecture 03

More from Mahmoud (20)

PDF
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
PDF
كيف تقوى ذاكرتك
PDF
مهارات التعامل مع الغير
PDF
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
PDF
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
PDF
كيف تقوى ذاكرتك
PDF
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
PDF
الشخصية العبقرية
PPT
Accident Investigation
PPT
Investigation Skills
PDF
Building Papers
PPTX
Operatingsystemwars 100209023952 Phpapp01
PDF
A Basic Modern Russian Grammar
PDF
Teams Ar
PDF
Stress Ar
PDF
Small Projects
PDF
Risk
PDF
Problem Ar
PDF
Negotiation Ar
PDF
Health Ar
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
كيف تقوى ذاكرتك
مهارات التعامل مع الغير
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
كيف تقوى ذاكرتك
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
الشخصية العبقرية
Accident Investigation
Investigation Skills
Building Papers
Operatingsystemwars 100209023952 Phpapp01
A Basic Modern Russian Grammar
Teams Ar
Stress Ar
Small Projects
Risk
Problem Ar
Negotiation Ar
Health Ar

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Electronic commerce courselecture one. Pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Big Data Technologies - Introduction.pptx
Machine learning based COVID-19 study performance prediction
Reach Out and Touch Someone: Haptics and Empathic Computing
MYSQL Presentation for SQL database connectivity
Chapter 3 Spatial Domain Image Processing.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Empathic Computing: Creating Shared Understanding
Programs and apps: productivity, graphics, security and other tools
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Electronic commerce courselecture one. Pdf
Per capita expenditure prediction using model stacking based on satellite ima...
sap open course for s4hana steps from ECC to s4
Unlocking AI with Model Context Protocol (MCP)
Building Integrated photovoltaic BIPV_UPV.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Encapsulation_ Review paper, used for researhc scholars
Dropbox Q2 2025 Financial Results & Investor Presentation
“AI and Expert System Decision Support & Business Intelligence Systems”
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

Assignment2 A

  • 1. CS193P Assignment 2A Winter 2010 Cannistraro/Shaffer Assignment 2A - WhatATool (Part II) Due Date This assignment is due by 11:59 PM, January 20. Assignment Now that we have some Objective-C experience under our belt, we’ll dive into the world of custom classes and more advanced Objective-C language topics. You will define and use a new custom class, and learn about Objective-C categories. We will use the same WhatATool project from last week as our starting point. A few more sections will be added to the existing structure. The basic layout of your program should look something like this: #import <Foundation/Foundation.h> // sample function for one section, use a similar function per section void PrintPathInfo() { // Code from path info section here } int main (int argc, const char * argv[]) { NSAutoreleasepool * pool = [[NSAutoreleasePool alloc] init]; PrintPathInfo(); // Section 1 PrintProcessInfo(); // Section 2 PrintBookmarkInfo(); // Section 3 PrintIntrospectionInfo(); // Section 4 PrintPolygonInfo(); // Section 6 (No function for section 5) [pool release]; return 0; } Testing In most assignments testing of the resulting application is the primary objective. In this case, testing/grading will be done both on the output of the tool, but also on the code of each section. We will be looking at the following: 1. Your project should build without errors or warnings. 2. Your project should run without crashing. 3. Each section of the assignment describes a number of log messages that should be printed. These should print. 4. Each section of the assignment describes certain classes and methodology to be used to generate those log messages – the code generating those messages should follow the described methodology, and not be simply hard-coded log messages. To help make the output of your program more readable, it would be helpful to put some kind of header or separator between each of the sections. Page 1 of 4
  • 2. CS193P Assignment 2A Winter 2010 Cannistraro/Shaffer Assignment Walkthrough Section 5: Creating a new class Create a PolygonShape class. To create the files for the new class in Xcode: 1. Choose File > New File… 2. In the Cocoa section under Mac OS X, select the ‘Objective-C class’ template 3. Name the file PolygonShape.m – Be certain the checkbox to create a header file is also checked Note that your new class inherits from NSObject by default, which happens to be what we want. Now that we’ve got a class, we need to give it some attributes. Objective-C 2.0 introduced a new mechanism for specifying and accessing attributes of an object. Classes can define “properties” which can be accessed by users of the class. While properties usually allow developers to avoid having to write boilerplate code for setting and getting attributes in their classes, they also allow classes to express how an attribute can be used or what memory management policies should be applied to a particular attribute. For example, a property can be defined to be read-only or that an when an object property is set how the ownership of that object should be handled. In this section you will add some properties to your PolygonShape class. 1. Add the following properties to your PolygonShape class •  numberOfSides – an int value •  minimumNumberOfSides – an int value • maximumNumberOfSides – an int value • angleInDegrees – a float value, readonly •  angleInRadians – a float value, readonly •  name – an NSString object, readonly 2. The numberOfSides, minimumNumberOfSides and maximumNumberOfSides properties should all be backed by instance variables of the appropriate type. These properties should all be synthesized. When a property is “synthesized” the compiler will generate accessor methods for the properties according to the attributes you specify in the @property declaration. For example, if you specified a property as “readonly” then the compiler will Page 2 of 4
  • 3. CS193P Assignment 2A Winter 2010 Cannistraro/Shaffer only generate a getter method but not a setter method. 3. Implement setter methods for each of the number of sides properties and enforce the following constraints: •  numberOfSides – between the minimum and maximum number of sides •  minimumNumberOfSides – greater than 2 • maximumNumberOfSides – less than or equal to 12 Attempts to set one of these properties outside of the constraints should fail and log an error message. For example, if you have a polygon that is configured with a maximumNumberOfSides set to 5 and you attempt to set the numberOfSides property to 9 you should log a message saying something like: Invalid number of sides: 9 is greater than the maximum of 5 allowed 4. Implement a custom initializer method that takes the number of sides for the polygon: - (id)initWithNumberOfSides:(int)sides minimumNumberOfSides:(int)min maximumNumberOfSides:(int)max; Your initializer should set the minimum and maximum number of sides first (to establish the constraints) and then set the number of sides to the value passed in. 5. Implement a custom init method (overriding the version implemented in NSObject) which calls your custom initializer with default values. For example, your generic -[PolygonShape init] method might create a 5 sided polygon with min of 3 sides and max of 10. 6. The angleInDegrees and angleInRadians properties should not be stored in an instance variable since they are all properties derived by the numberOfSides. These properties do not need to be synthesized and you should implement methods for each of them which return the appropriate values. We’re being boring and using regular polygons so the angles are all the same. 7. Similarly, the name property should also not be synthesized (nor stored in an instance variable) and you should implement a method for it. The name of the polygon should be a descriptive name for the number of sides. For example, if a polygon has 3 sides it is a “Triangle” A 4-sided polygon is a “Square” . . 8. Give your PolygonShape class a -description method. Example output from this method: Hello I am a 4-sided polygon (aka a Square) with angles of 90 degrees (1.570796 radians). 9. In order to verify your memory management techniques, implement a dealloc method and include an NSLog statement indicating that dealloc is being called. Section Hints: • You can find a list of names for polygons on the web. Wikipedia has a good one. • The formula for computing the internal angle of a regular polygon in degrees is (180 * (numberOfSides - 2) / numberOfSides). • Remember your trigonometry: 360° is equal to 2π. Page 3 of 4
  • 4. CS193P Assignment 2A Winter 2010 Cannistraro/Shaffer • You can use the preprocessor value M_PI for π. Section 6: Using the PolygonShape class Write a C function (e.g. PrintPolygonInfo) called by main() that uses your newly created PolygonShape class. You will have to add an import statement to the WhatATool.m file: #import "PolygonShape.h" IMPORTANT: In this section, you are expected to use +alloc and –init methods to create the polygons and the array that they are put into. You must practice correct memory management techniques of releasing the polygon objects when you are done with them. 1. Create a mutable array (using alloc/init). 2. Create 3 (or more) PolygonShape instances with the following values: Min number of sides Max number of sides Number of sides 3 7 4 5 9 6 9 12 12 When allocating your polygons, use a mixture of vanilla alloc/init then set the properties along with using your custom initializer method that takes all of the properties in the initializer method. 3. As you create each polygon, add them to the array of polygons and emit a log with the polygon’s description. There should be at least 3 descriptions logged. 4. Test the constraints on your polygons. Iterate over the array of polygons and attempt to set their numberOfSides properties to 10. This should generate two logs indicating that the number of sides doesn’t fall within the constraints (for the first two polygons in the table above). 5. Verify that your polygon objects are being deallocated correctly. If you have followed the rules correctly with regard to memory management you should see 3 logs from the dealloc method of your polygons. If you do not see these logs, review your alloc/init and release calls to make sure they are correctly balanced for your polygon objects as well as the array you are putting them into. Remember, alloc/init and release work like malloc and free in C. Page 4 of 4