Laboratory‎ > ‎

Objective-C


Objective oriented programming

  • Class: type; declare state and behavior; defines the grouping of data and code; blueprint to create instances
  • State(data): maintained using by instance variables
    • Instance: specific allocation of a class
    • Instance Variable(ivar): a specific piece of data belonging to an object, typically hidden
  • Behavior, implemented by methods
    • Method: a function of how to perform
  • Encapsulation: keep implementation private and separate from interface
  • Polymorphism: different objects, same interface
  • Inheritance: hierarchical organization in which a subclass inherits the behavior of a superclass

Objective-C 2.0 Programming language A guideline by Apple Developers


Message syntax

  • Instances --
  • Classes ++
Person *voter; //assume this exists 
[voter castBallot]; 
int theAge = [voter age]; 
[voter setAge:21];
if ([voter canLegallyVote]) { 
// do something voter-y
} 
[voter registerForState:@"CA" party:@"Independant"]; 
NSString *name = [[voter spouse] name];
  • Dot syntax: [person height] equivalent to person.height

Types

  • Dynamic/static(*): compile-time type checking, Obj-C always uses dynamic binding
  • Null object pointer: =nil;
  • BOOL typedef: =YES/NO;
  • Selectors SEL: e.g. SEL sel = @selector(start:);

Class introspection

//inquire an object about its class
Class myClass = [myObject class];
NSLog(@"My class is %@", [myObject className]);
 
//testing for general class membership (subclasses included):
if ([myObject isKindOfClass:[UIControl class]]) { 
// something
}
 
//testing for specific class membership (subclasses excluded):
if ([myObject isMemberOfClass:[NSString class]]) { 
// something string specific
}

Objects

  • Identity: testing whether the pointer values are the same
if (object1 == object2)
  • Equality: testing object attributes
if ([object1 isEqual: object2])
  • String object to be preceded by %/@
e.g. [NSString stringWithFormat: @"The answer is: %@", myObject];

Foundation Framework

  • NSObject: root class; memory management, introspection, object equality
  • NSString: general-purpose Unicode string
    • NSLog: equivalent to printf
    • common methods: (BOOL)isEqualToString: (NSString *)string;, (BOOL)hasPrefix: (NSString *)string;, (int)intValue;, (double)doubleValue;
NSString *aString = @"Hello World!";
if ([aString hasPrefix:@"He"]) {
   // will make it here
}
  • NSMutableString
    • Collections: array, dictionary(collection of key-value pairs), set
    • common enumeration mechanism
  • NSArray: nil termination

Classes

Class definition

.h public header
.m private implementation
=== e.g. Header:Person.h ===
#import <Foundation/Foundation.h>
 
@interface Person : NSObject 
{
  // instance variables 
  NSString *name; 
  int age;
}
 
// method declarations 
- (NSString *)name; 
- (void)setName:(NSString *)value;
 
- (int)age; 
- (void)setAge:(int)age;
 
- (BOOL)canLegallyVote; 
- (void)castBallot;
@end
=== e.g. Implementation:Person.c ===
#import "Person.h"
 
@implementation Person
 
- (BOOL)canLegallyVote {
  return ([self age] >= 18);
} 
 
- (void)castBallot {
  if ([self canLegallyVote]) {
    // do voting stuff
  } else { 
    NSLog (@“I’m not allowed to vote!);
  }
} 
@end
  • Superclass methods
[super doSomething];

Object

  • +alloc allocate memory to store the object
  • +init initialize object state
Person *person = nil;
person = [[Person alloc] init];
AllocationDestruction
Cmallocfree
Obj-Callocdealloc
  • Reference counting
    • object alive if retain count > 0
    • +alloc|-copy : retain count = 1
    • -retain: count++
    • -release: count--
    • if retain count=0, -dealloc invoked automatically
    • -autorelease: releases later/after return (in the last stage of handle event cycle)
Person *person = [[Person alloc] init];
// Retain count begins at 1 with +alloc
[person retain];
// Retain count increases to 2 with -retain
[person release];
// Retain count decreases to 1 with -release
[person release];
// Retain count decreases to 0, -dealloc automatically called
  • Properties: access to object attributes
    • getter/setter methods implementation
    • specify read-only vs. read-write
@property int age; // read-write by default 
 @property (readonly) BOOL canLegallyVote;
 
// Memory management policies (only for object properties)
@property (assign) NSString *name; // pointer assignment 
@property (retain) NSString *name; // retain called 
@property (copy) NSString *name;	// copy called
  • Dot syntax
@implementation Person 
- (void)doSomething {
  name = @“Fred”; 
  self.name = @“Fred”;
}

Controls

  • Delegation: control passed to delegate objects to perform application-specific behavior

Anatomy

  1. Model = data & state
  2. View = UI
  3. Controller = intermediary between model & view

Nib files: layout user interface elements, add controller objects, connect controller & UI

Controls and target-action

- (void)actionMethod; 
- (void)actionMethod:(id)sender; 
- (void)actionMethod:(id)sender withEvent:(UIEvent *)event;

UIScrollView
  • panning and zooming, for displaying more content than can fit in the screen
    • Content size = contentSize.width x contentSize.height
    • Content inset: contentInSet.top, bottom, left, right
    • Content offset: contentOffset.x, contentOffset.y
  • ScrollView creation
CGRect frame = CGRectMake(0, 0, 200, 200); 
scrollView = [[UIScrollView alloc] initWithFrame:frame];
  • Add subviews
frame = CGRectMake(0, 0, 500, 500); 
myImageView = [[UIImageView alloc] initWithFrame:frame]; 
[scrollView addSubview:myImageView];
scrollView.contentSize = CGSizeMake(500, 500);
  • Zooming
scrollView.maximumZoomScale = 2.0; 
scrollView.minimumZoomScale = scrollView.size.width / myImage.size.width;
 
// Delegate implementation
- (UIView *)viewForZoomingInScrollView:(UIView *)view {
}
return someViewThatWillBeScaled;
}
// Set zoom scale
- (void)setZoomScale:(float)scale animated:(BOOL);
- (void)zoomToRect:(CGRect)rect animated:(BOOL);

Table Views
single column, multiple rows, vertical scrolling, large data sets
// Provide number of sections and rows
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section;
// Provide cells for table view as needed
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath;
  • Section and row reloading
- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
  • Response
// For a navigation hierarchy...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
// Get the row and the object it represents
NSUInteger row = indexPath.row id objectToDisplay = [myObjects objectAtIndex:row];
// Create a new view controller and pass it along
MyViewController *myViewController = ...; myViewController.object = objectToDisplay;
[self.navigationController pushViewController:myViewController animated:YES];

MacOSX application development

Almost all academic research is being done on Unix environment; therefore, majority of people in academia stick with Linux despite its ambiguity. Luckily, MacOSX is unix-based operating system which provides ease of use, as well as powerful performance, and compatibility with unix applications. This is simple how to setup a mac for own research and apparently, currently ongoing application development.

  • XCode

The first thing you all probably need is to install xCode. Apple incorporates all prerequisites, including basic programming tools, support for various programming languages, compilers into a single developmental suite xCode. By installing xCode, you will be set to go.

  • Darwin Ports

In order to install other unix program in MacOS, one may try typing configure, make, then make install for all programs. However, that's just too much time and labor, since a lot of programs require prerequisites before making installation, and many do not tell you what you need in firsthand. Darwin Ports is a great tool which can figure out what other applications needed to be installed, and grabs source itself, and installs automatically. Darwin ports is a great open source environment for Mac users and itself is an automator. Once you have installed the program (install DarwinPorts), you may install other applications by typing following commands in terminal.

Setting up the shell environment (add /opt/local/bin to path)

echo 'export PATH=/opt/local/bin:/opt/local/sbin:$PATH' >> ~/.bash_profile
echo 'export DISPLAY=:0.0' >> ~/.bash_profile

Usage (e.g. installing xfig):

 sudo port -d selfupdate update to current version
 sudo port install xfig fetch and install xfig and its prerequisites
  • Apple Darwin kernel cross reference
  • MacOS apps serial lookup
  • Screenshot shortcuts
    • command+shift+3 saves the desktop screenshot to the desktop folder
    • command+control+shift+3 copies the desktop to the clipboard
    • command+shift+4 to capture a portion of the desktop
    • command+shift+4 then press space bar to capture a specific application window

Simple bash commands

ln -s /some/name         # creates link ./name pointing to /some/name
ln -s /some/name spud    # creates link ./spud pointing to /some/name
ln -s a b ..             # creates links ../a and ../b pointing to ./a and ./b

Reference

Comments