Monday 4 January 2010

Cocoa Framework Summary

A summary by James Bedford.

Cocoa is a framework of tools used for software development written in Objective-C, featuring modular, object-oriented and visual design. It was originally called NextSTEP and was developed by the company NeXT. When NeXT merged with Apple in 1996, the framework NextSTEP was renamed Cocoa. However, it still remains that all objects within this framework begin with the prefix "NS", which helps to distinguished them and prevent accident errors.


This summary is work-in-progress (which will be periodically updated) and may contain mistakes. Please let me know if there are any issues, or if anything needs clarifying.


These notes are intended to be read with "Objective-C Programming Language Summary by James Bedford" as well as the Apple Developer Documentation.



Foundation Framework:



  • NSArray

    • You can put any type of Object into an NSArray.

    • arrayWithObjects: (id) …

      • creates an NSArray with the following objects, returns a pointer to it. The last object in the array must be "nil".



    • count - returns the number of objects in the NSArray.

    • objectAtIndex: (unsigned int)

      • returns a pointer to the object at the index of NSArray.



    • objectEnumerator

      • returns an NSEnumerator.



    • reverseObjectEnumerator

      • as above if you want to walk from back to front.



    • Can be traversed quickly using "for in" (or an enumerator).

      • e.g. "for (NSString * string in array) { // do something }"





  • NSMutableArray

    • Extends NSArray.

    • arrayWithCapacity: (unsigned)

      • returns a new NSMutableArray with an initial capacity of that supplied.



    • addObject: (id)

      • adds the object supplied to the end of the array. Void method.



    • removeObjectAtIndex: (unsigned)

      • removes the object at the index and shifts all the other objects down to fill the gap. Void method.



    • replaceObjectAtIndex: (int) withObject: (id)

      • Replaces the object at the index provided with a pointer to the new object provided.





  • NSComparisonResult

    • Enum

    • { NSOrderedAscending = -1, NSOrderedSame, NSOrderedDecending}

    • I presume this is short hand for three options, -1, 0, and 1 respectively.



  • NSData

    • An object-oriented wrapper for a byte buffer.

    • Used in file handling.

    • writeToUrl: (NSURL*) atomically: (BOOL)

      • Writes the data in the NSData object to the file determined by the NSURL object supplied.

      • If atomically is YES, then the data first gets written to an auxiliary file, which then gets renamed to the NSURL file path. If this is NO, then the data gets written to the file path directly.





  • NSDictionary

    • Also known as a hash table. Like a map.

    • dictionaryWithObjectsAndKeys: (id), …

    • creates a dictionary, alternating between object then key and terminated by a nil value.

    • objectForKey: (id)

      • returns a pointer to an object with the key of the object provided.





  • NSMutableDictionary

    • Extends NSDictionary

    • dictionaryWithCapacity: (unsigned int)

      • creates an NSMutableDictionary of the initial size provided.



    • setObject: (id) forKey: (id)

      • adds an object to the dictionary using the key provided. If the key's already there it replaces the object it's linked to.



    • removeObjectForKey: (id)

      • removed the object from the Dictionary that has this key.





  • NSDate

    • date

      • Class method.

      • Returns a new date set to the current date.



    • descriptionWithCalenderFormat: (NSString *) timeZone: (NSTimeZone *) locale: (id) localeDictionary

      • All variables can be set to "nil" for their default settings.

      • Prints the date using the format given by the NSString.

      • Date format specifiers:

        • %B = name of the month.

        • %m = numerical representation of the month.

        • %e = numerical representation of the day of the month.

        • %d = as above but as a two-digit value.

        • %A = name of the weekday.

        • %I = hours.

        • %M = minutes.

        • %S = seconds.

        • %Y = year.







  • NSEnumerator

    • nextObject

      • gets a pointer to the next object.





  • NSDirectoryEnumerator

    • Extends NSEnumerator.

    • Each time nextObject is called the next file is returned until there are no more files (nil is returned).



  • NSFileManager

    • defaultManager - created and returns a pointer to a standard NSFileManager.

    • Use a file path stored as an NSString with this.

    • fileAttributesAtPath: (NEED TYPE) traveseLink: (BOOL) - returns an NSDictionary with properties about the file. With this, you can use keys 'NSFileSize' and 'NSModificationDate' to store their values into an NSNumber and NSDate respectively.

    • enumeratorAtPath: (NSString *) - returns an NSDirectoryEnumerator for traversing files, starting at the path supplied in the NSString.



  • NSFileWrapper

    • Stores a file's data into memory.



  • NSObject

    • All classes are a subclass of this.



  • NSOpenPanel

    • A subclass of NSWindow that allows the user to find a file.

    • Four steps to using this:

      • Create an instance of NSOpenPanel.

      • Set the attributes of this instance.

      • Display the instance for the user and wait for the user's response (selecting a file and clicking OK or cancelling).

      • Perform a function with the file the user selected.





  • NSPoint

    • Struct.

    • Holds 2 floats, x and y.

    • Can be initialised using the convenience function NSMakePoint, or simply using standard C structs.



  • NSRange

    • Struct.

    • Holds 2 unsigned ints; location and length.

    • Can be initialised using the convenience function NSMakeRange(int, int), or simply using standard C structs.



  • NSNull

    • null - A single method that creates and returns a pointer to an NSNull.

    • NSNull is used when you want to add a null value to an NSArray or NSDictionary (as the value nil terminates the NSArray or NSDictionary).

    • You can use == to compare NSNull to other values.

    • Is printed to the standard output as "<null>";



  • NSNotFound

    • A value that represents a string not being found which can be returned by functions.



  • NSNumber

    • Extends NSValue.

    • Boxes a primitive number.

    • numberWithChar: (char) - makes an NSNumber using a supplied char.

    • There are similar methods for int, float, double, BOOL, etc.

    • charValue - returns a char of the NSNumber.

    • There are similar accessor methods for all types, e.g. charValue, intValue, doubleValue etc.

    • isEqualToNumber: (int/double etc.)

      • Returns a BOOL representing whether the two NSNumbers are equal or not.

      • Saves un-boxing.





  • NSNumberFormatter

    • Regulates the format of numbers.

    • setFormat: (NSString *) sets the format that the instance of the class allows. The string provided specifies the format(s).



  • NSRect

    • Struct.

    • Holds an NSPoint origin and an NSSize size.

    • Can be initialised using the convenience function NSMakeRect, or simply using standard C structs.



  • NSSize

    • Struct.

    • Holds two floats, width and height.

    • Can be initialised using the convenience function NSMakeSize, or simply using standard C structs.





  • NSString

    • A literal NSString can be written using double quotes and the @ symbol. E.g. name = @"James";

    • stringWithFormat: is a factory method that creates a new NSString using format specifiers, such as %d and %@.

    • length returns an unsigned int which is the length of the NSString.

    • isEqualToString: (NSString *) returns a BOOL value of the two NSStrings being equal.

    • compare: (NSString *) returns an NSComparisionResult after comparing the two NSStrings. Case sensitive.

    • compare: (NSString *) options: (unsigned) gives more control over the comparison.

      • Logical or together things like NSCaseInsensitiveSearch, NSLiteralSearch, NSNumericSearch.



    • hasPrefix: (NSString *) returns a bool representing if the NSString starts the string.

    • hasSuffix: (NSString *) as above only for suffixes.

    • rangeOfString: (NSString * ) returns an NSRange with a value of NSRange.start to be the position the NSString is found at (or an NSNotFound if not found), and an NSRange.length set to the length of the NSString found.

    • componentsSeparatedByString: (NSString *) - returns a new NSArray by splitting the NSString using the given NSString as the split points.

    • stringByExpandingTildeInPath - returns an NSString created using a string with a tilde.

    • writeToFile: (NSURL *) atomically: (BOOL) encoding: (NSStringEncoding) error: (NSError **)

      • Writes the file to the file path provided in the NSURL.

      • If atomically is YES, then the file is written to an auxiliary file, which is then renamed to the file path determined in the NSURL. If NO, then it writes directly to the file path in NSURL.

      • The NSStringEncoding specifies the encoding type to use.

      • Error can be set to NULL. I don't really understand this otherwise but it's about getting error data back if there's a problem writing the file.

      • Returns a BOOL representing whether the write was successful or not.





  • NSStringEncoding

    • An enum representing all kinds of different ways of encoding text.

    • Some examples:

      • NSASCIIStringEncoding

      • NSUTF8StringEncoding

      • NSMacOSRomanStringEncoding





  • NSMutableString

    • Extends NSString.

    • stringWithCapacity: (unsigned) capacity - returns a new NSMutableString with an initial capacity as provided.

    • appendString: (NSString *) - appends the given NSString to the NSString. Void method.

    • appendFormat: (NSString * ) , ... - as above but allows formatting.

    • deleteCharactersInRange: (NSRange) - deletes the characters in the range provided.





  • NSURL

    • Represents a URL information.

    • Used with file locations and web addresses.



  • NSValue

    • valueWithBytes: (const void *) objCType: (const char *) - creates an NSValue of the original primitive C type provided, and an array of characters which act as a label describing the type.

    • @encode can be used to produce the array of characters of the type. e.g. "@encode(NSRect)". This is an Objective-C compiler directive.

    • getValue: (void *) - stores the address of the value stored in NSValue in the pointer provided. Void method.





  • NSWorkspace

    • Every application has one and only one instance of this.






AppKit Framework (Application Kit):



  • The idea with all of the classes in the AppKit is to drag them and resize them using the Interface Builder, and then link them to a controller class, and the write the code that determines the classes behaviour in the controller.

  • Building controller classes (see MVC design):

    • A controller class is a class that aims to link the view to the model. It will extend NSObject, and has various IBOutlet instance variables and IBAction methods.

    • IBOutlet

      • Data type. It's an AppKit #define to be nothing, so is ignored at compile time. However, it let's the interface builder know that this is an outlet, so it can be linked to an appropriate GUI widget. Example use:

        • " IBOutlet NSTextField * textField; "

        • Used as an instance variable defined in the @interface section of the controller class.



      • Can also be added to a controller class using the identity inspector in the Interface Builder.



    • IBAction

      • Data type. It's an AppKit #define to be void. Similarly to IBOutlets, IBAction lets the interface builder know that a method defined with IBAction can be called by a GUI widget, such as clicking a button. Example use:

        • " - (IBAction) updateScores: (id) sender; "

        • This is an instance method defined in the @interface section of a controller class.

        • WRITE ABOUT ID SENDER.



      • Can also be added to a controller class using the identity inspector in the Interface Builder.



    • It's also possible to create a controller class in the interface builder by adding a new NSObject to the project window, renaming it, adding outlets, making connections to widgets (as above) and then selecting 'File -> Write Class Files' from the IB menu. The superclass of this class must then be specified in Xcode.



  • Updating controller classes using the Interface Builder:

    • Drag new widgets to the design window.

    • Connect the widgets to the controller using the method described above.

    • Choose 'File -> Write Class Files' and then select 'merge' to add the new outlets created and linked in the interface builder to the controller class.

    • IB then launches the application FileMerge, which deals with the merge.

    • Sometimes it's easier to edit the interface and implementation files in Xcode.



  • Creating a sheet for a Window:

    • A sheet is a window that folds down from the top of another window. It prevents interaction with it's parent window (below it), and won't go until the user has made a decision.

    • To make one in the Interface Builder:

      • Drag a panel from the Library to the Project Window.

      • In the Inspector Window for this panel, deselect all the Style and Controls settings.

      • Add a button to the panel using the Design Window (this will close the sheet) and ensure there's some widget that will open the sheet in the sheet's parent window.

      • Ensure there is a controller class. Add two IBOutlets (one for theParentWindow and one for theSheet). Add two IBActions (one for the button to close the sheet, and one for the method of opening the sheet).

      • Link up the controller's outlets and actions (using control-click-drag) to the relevant GUI widgets and windows.

      • In the open sheet method, call the beginSheet: class method of the NSApp class.

      • In the close sheet method, call the orderOut: method to theSheet IBOutlet and call the endSheet: theSheet class method of the NSApp class.





  • Delegates

    • Letting a class handle specific events, for example, every time a window hides a class could do something in response.

    • To assign delegate status to a class, control-drag from the GUI widget (e.g. a Window) to the class and select "Delegate" from the pop up list.

    • You can then implement delegate methods defined in the widget classes.



  • NSButtons

    • All buttons in Cocoa are of this type.

    • Push Button

      • Most common Mac OS button.

      • Rounded edges with a centred text label.

      • Triggers an action when pressed.



    • Round Button

      • As with a bush button, but with more rounded edges, and can also display an image as well as text.



    • Check Box

      • Doesn't trigger an action.

      • state

        • Returns a BOOL representing whether or not the check box is ticked.





    • Bevel Buttons

      • Can mimic other controls.

      • Can show a depressed look.

      • Can display a selection of choices like a menu.



    • Radio Control

      • Multiple options, but only one can be selected at a time.

      • Store multiple radio buttons (options) in cells in an NSMatrix.

      • Connect the NSMatrix to a controller IBOutlet, not individual radio controls.

      • NSMatrix

        • selectedRow

          • Returns the index of the currently selected row (the first row is at the top with an index of 0).









  • NSColor

    • Represents a color.



  • NSColorWell

    • setColor: (NSColor *)

      • Sets the currently selected color to the NSColor provided.

      • Useful for setting default values.



    • color

      • Returns an NSColor representing the currently selected color.





  • NSIndicator

    • Two types:

    • Indeterminate

      • When the process will take an unknown amount of time.

      • startAnimation

        • Causes the barer poe to move.





    • Determiniate

      • When the process time is known.

      • setMinValue:

        • Sets the minimum value the indicator will take.



      • setMaxValue:

        • Sets the maximum value the indicator will take, when this value is reached, the process will have completed.



      • setDoubleValue: (Double)

        • Sets the current progress of the indicator to the double provided.







  • NSPanel

    • Extends NSWindow.

    • INCOMPLETE NOTES.



  • NSSlider

    • Subclass of NSControl.

    • A control that represents a range of values.

    • Can be horizontal, vertical, or circular options.

    • Can be continuous or discrete.

    • intValue

      • Returns the current value of the control.

      • Can also use floatValue, doubleValue etc.



    • setIntValue: (int)

      • Sets the current value of the control to the integer provided.

      • Can also use setFloatValue, setDoubleValue etc.





  • NSTableView

    • Used for displaying a lot of data in various different ways.

    • After the table has been connected to a controller, I think that methods must be written into the controller that determine the table's behaviour that get called.



  • NSTabView

    • Allows multiple tabs and a selector between tabs.

    • Specifier the number of tabs in the Attributes Inspector Window.

    • Selecting the tab in the design view allows you to add controls to that section of the tab.

    • A tab is an NSTabViewItem.

    • To find out index of the tab that's open, use indexOfTabViewItem and selectedTabViewItem (see below).

    • indexOfTabViewItem: (NSTabViewItem *)

      • Returns the index of the item given in the tab view.



    • selectedTabViewItem

      • Returns a pointer to the currently selected NSTabViewItem.





  • NSTextField

    • stringValue

      • Returns an (NSString *) of the text in the NSTextField.



    • setStringValue: (NSString *)

      • Sets the contents of the text field to the string provided.

      • If the text field widget isn't big enough to display all the text, the text field just displays as much of the string as it can.



    • setIntValue: (int)

      • You can replace 'int' with any C data type.

      • Sets the label to be the value given as a method parameter.





  • NSText

    • A more primitive class that handles text. Most use will come from its subclass, NSTextView.

    • RTFFromRange: (NSRange)

      • Returns an NSData object that contains an RTF stream of the contents of the text within the range.

      • Can throw an NSRangeException.





  • NSTextView

    • Extends NSText.

    • The application TextEdit is basically just a single window with an NSTextView that fills the window.

    • selectedRange

      • Returns an NSRange that holds the text currently selected in the Text View.



    • setTextColor: (NSColor *)

      • Sets the color of the text in the Text View to the color provided.



    • setTextColor: (NSColor *) range: (NSRange)

      • As above but for the text in the range. See the above to methods.



    • toggleRuler: (BOOL)

      • Sets the ruler to the state indicated by the BOOL provided (I think).



    • string

      • Returns an NSString object of the contents of the Text View.



    • setString: (NSString *)

      • Sets the text in the Text View to be the string provided.



    • replaceCharactersInRange: (NSRange) withString: (NSString *)

      • Self explanatory.





  • NSSavePanel

    • Extends NSPanel.

    • savePanel

      • Class method. Creates a new NSSavePanel and returns a pointer to it.



    • setRequiredFileType: (NSString *)

      • Sets the required file type to save as to be that give in the NSString.

      • e.g. @".txt"



    • runModal

      • "Displays the panel and begins its event loop with the current working (or last selected) directory as the default starting point." - Developer Documentation.

      • Returns an NSFileHandlingPanelOKButton if the user clicked the save button, else a NSFileHandlingPanelCancelButton if the user clicked cancel.

      • Using the information in the above bullet point, write code to determine how the file is saved or not.



    • URL

      • Returns an NSURL representing the pathname of the file the user determined using the Save Panel.





  • NSWindow

    • Extends NSResponder.

    • close

      • Removes the window from view. See the preliminary method below.



    • setReleasedWhenClosed: (BOOL)

      • Sets whether or not the contents of the window are released from memory when the window is closed. Default NSWindow's are set to NO.



    • setTitle: (NSString *)

      • Sets the windows title to the string provided.



    • setTitleWithRepresentedFilename: (NSString *)

      • As above, but ideal for setting the title bar to a file name. Converts a file path if necessary.



    • setAlphaValue: (double)

      • Sets the transparency of the window. Takes an integer between 0 and 1.



    • makeKeyAndOrderFront: self

      • Displays the window and moves it to the front.



    • orderOut: (id) sender

      • Hides the window.

      • The window is still stored in memory.



    • orderFront: (id) sender

      • Makes the window visible.



    • isVisible

      • Returns a BOOL indicating whether or not the NSWindow is visible.



    • frame

      • Returns an NSRect containing an NSPoint origin and an NSSize size of the NSWindow.



    • zoom

      • Zooms the window.





  • NSWorkspace

    • Can be used to find out things like the setup the program is currently running under

    • launchedApplications

      • Returns an NSArray of all currently running applications.








MVC Design



  • Model-View-Controller design pattern.

  • Model

    • An object that provides data to your application.



  • View

    • An object that displays data in your application.

    • Is often the interface to the application.

    • Most commonly a GUI, which can be built using Apple's Interface Builder.



  • Controller

    • An intermediary object that obtains data from the Model and passes it to the View for display. The controller may modify the model using information gathered from the View.

    • Can be thought of as a fuse box.



  • Real-world example of Student (Controller), Dictionary (Model) and Blackboard (Model).



Interface Builder (IB) - GUI Development Tool





  • Edits .xib files.

    • Pronounced "nib" - short for NextSTEP interface builder.

    • .xib files (introduced with Xcode 3) are written in XML format, and are compiled into .nib format.



  • Press ⌘R to test the interface (no working code required).

  • An application gets some information (such as its name and version) from Info.plist.

    • This file consists of XML, and can be parsed in Xcode or the Property List Editor.



  • Project Window (Main Nib File Window)

    • Used to store components of the nib file.

    • Displays icons representing the contents of the nib file.

    • Has three different views.

      • Icon: default, and good to get an overview.

      • List: hierarchical, and useful for looking into objects (such as a window).

      • Column: As for list, although the hierarchical layout is displayed in columns.



    • A newly created .xib file comes with six default items that can be found in the project window:

      • File's Owner

      • First Responder

      • Font Manager

      • Application

      • MainMenu

        • Used to edit the menus for your interface in the menu editor window.



      • Window





  • Design Window

    • Used for creating visual way a program will look.



  • Menu Editor

    • Used to create, edit or delete menus that will appear when the application is focused.



  • Library Palette

    • Holds objects and widgets that can be dragged into your nib file.



  • Inspector Window

    • Used to edit attributes and properties of the interface and classes within it.

    • Has the following sections:

    • Attributes (1)

      • ADD NOTES.



    • Connections (5)

      • ADD NOTES.



    • Identity Inspector (6)

      • ADD NOTES.

      • Displays and allows changes or additions to controller IBOutlets and IBActions.







  • Adding a controller object to the nib file:

    • Drag an NSObject to the main nib file window.

    • Change the objects class using the identity inspector.



  • Connecting a view to a controller:

    • IBOutlet:

      • Controller to widget.

      • Hold down the control key and click and drag from the controller class (in the main nib file window) to the GUI widget.

      • A menu will pop up with the controller classes's IBOutlets. Select the appropriate outlet to link it to the GUI widget.



    • IBAction:

      • Widget to controller.

      • Hold down the control key and click and drag from the GUI widget to the controller class (in the main nib file window).

      • A menu will pop up with the controller classes's IBActions. Select the appropriate action to link the GUI widget's action event with the controller's IBAction method.





  • How Nib Files Work

    • Nib file is loaded:

      • All objects in the nib file are created using alloc and init.

      • Connections are made (the address of the widget objects are put into into the controller's instance variables).

      • An awakeFromNib message is sent to every object that was created (in no predefined order).








Icon Composer (Icon Development Tool)



  • Used to convert 512 x 512 pixel .png image files into icons.

  • Icon files can then be loaded into an Xcode project. Set the icon file name in the Info.plist file in order to get an application to display this icon.




Key-Value Coding



  • This is another way of accessing instance variables and components of objects.

  • valueForKey: (NSString)

    • Returns the value stored in the variable identified by NSString.

    • First looks for an appropriate getter method. If there is none, it looks inside the object (!) for the variable directly.

    • Automatically boxes primitive variables.



  • setValue: <VALUE> forKey: (NSString)

    • First looks for an appropriate setter method. If there is none, it looks inside the object (!) for the variable directly and then assigns it the new value..

    • Automatically unboxes primitive variables. So you must box primitives before passing them to the setValue: parameter.

    • If you want to set a nil value, you need to override the setNilValueForKey: (NSString *) method in the class of the object you want to do this in - otherwise you'll get a runtime error.



  • valueForKeyPath: (NSString)

    • As for valueForKey: - but you can supply a chain such as @"building.floor1.room5.size" where each section is an object within the building composition, and size is the final instance variable.



  • setValue: <VALUE> forKeyPath: (NSString)

    • As for valueForKeyPath AND setValue.



  • dictionaryWithValuesForKeys: (NSArray *)

    • You must supply an array of NSStrings.

    • Returns a dictionary mapping the values of the instance variables of the object that was sent the message to the strings provided in the NSArray.

    • e.g. NSDictionary * floorValues = [building dictionaryWithValuesForKeys: anArrayOfVariablesIWant];



  • setValuesForKeysWithDictionary: (NSDictionary *)

    • Sets all the instance variables of the object this message is sent to with the values and keys provided in the NSDictionary (which is set up before this call).



  • NSArray

    • If you use a valueForKey method for an NSArray, it asks each element in the array for the key, and returns an NSArray with the results (all the values of the keys asked for).



  • Key Path Operators

    • Used in arrays.

    • Used as follows:

      • valueForKeyPath: @"<array>.<operator>.<element_of_array_instance_variable>"

      • Array is to the left of the operator (separated by a .) and the element of the instance of the array to be checked on each occasion is to the right of the operator (again separated by a .).

      • Operators are as follows…



    • @count

      • Counts the property before it.

      • e.g. [building valueForKeyPath: @"floors.@sum"];

      • This returns the number of floors in the building, where floors is an NSArray within an object building.



    • @sum

      • Totals values.

      • e.g. [building valueForKeyPath: @"floors.@sum.size"];

      • This would total the size of all the floors, where size is a number that is a parameter of floor.



    • @avg

      • Takes the average of all the values provided.

      • e.g. [building valueForKeyPath: @"floors.@avg.size"];

      • This would find the average side of a floor and return it.



    • @min

      • Returns the minimum value.



    • @max

      • Returns the maximum value.



    • @distinctUnionOfObjects

      • Returns all the different values that the instance variable takes within this array.





  • valueForUndefinedKey: (NSString *)

    • Override this method in order to handle the case in which a key cannot be found when looking up the key.



  • setValue: (id) forUndefinedKey: (NSString *)

    • Override this method in order to handle the case in which a key cannot be found when trying to set a key.



  • Weaknesses of Key Value Coding:

    • It's slower - less efficient.

    • A runtime error can be thrown if the instance variable cannot be found.




That's all for now! :)

2 comments: