tags | languages |
---|---|
categories, object-oriented, nsnumber, nsinteger |
objc |
- Take a look at the tests we have for this project. You can find them in
UnitTests/Tests/NSNumber+FISMathSpec.m
- You'll see that they attempt to import
NSNumber+FISMath.h
. You're getting errors right now because that file doesn't exist. So let's make our first category:
- File -> New File... -> Source: Objective-C File
- Name your category FISMath
- Select File Type: Category
- Select Class: NSNumber <- this is the class that we're adding a category to, in this case NSNumber
- Awesome! So the file that gets created is an empty category called
FISMath
that will allow us to add to the functionality of NSNumber. - Declare 4 methods in the
FISMath
category interface and define them in the implementation file. For now, assume theNSNumbers
all containNSInteger
s.
add:(NSNumber *)number
that returns theNSNumber
sum of the receiver and theNSNumber
that is passed in as a parametersubtract:(NSNumber *)number
that returns theNSNumber
difference of the receiver and theNSNumber
that is passed in as a parametermultiplyBy:(NSNumber *)number
that returns theNSNumber
product of the receiver and theNSNumber
that is passed in as a parameterdivideBy:(NSNumber *)number
that returns anNSNumber
that is the receiver divided by theNSNumber
that is passed in as a parameter
- For more information, examine the tests in the
NSNumber+FISMathSpec.m
file - Make the tests pass!
- First add in the
ADVANCED
pre-processor macro to turn on the advanced tests. - In Xcode, switch to the file browser in the left pane. Select the project itself (the first item, "CategoryMath", with the blue icon). Now, in the main pane, select "UnitTests" under "Targets", and switch to the "Build Settings" tab. Search in there for "preprocessor", and double click the column after "Prepocessor Macros". In the window that pops up, hit the plus, enter "ADVANCED", and hit enter. See the picture below for more clarity: - Now let's make our category work a bit better. Right now it only works on integers because we converted everything to an
NSInteger
before doing the math. The problem is this should work for any type ofNSNumber
, from floating point to unsigned integer. There is a method onNSNumber
calledobjCType
that will tell you what type of number a givenNSNumber
instance contains. Use that so that our category works on all types of numbers. - The advanced tests assume you will write these methods in a category calledFISMathAdvanced
, and name themadvancedAdd:
,advancedSubtract:
, and so on.