Sei sulla pagina 1di 2

Chapter 1

Sub classing an objective C class: NSMutable array inherit from


NSArray, NSArray and NSString inherit from NSObject
(NSString*)description {return @a}; NSLog(%@, p)
InitwithObject {self = [super init]; return self}, id is defined as pointer
to any objects
Automatic Reference Counting (ARC) = Garbage Collector
-Pointer Variable and Object Ownership
Case1: A method has a local variable that point to an object
Case2: An object has an instance variable that points to another object
-Memory Management
Loosing ownership doesnt necessary mean the object get destroy
Strong - Anytime a pointer variable stores the address of an object,
that object has an owner and will stay alive
Weak - A variable that doesnt take ownership of an object. It is useful
for an unusual situation called a retain cycle.

Atomic
Nonatomic
Any implementation we add will override the synthesized version
Block Declaration declare as
Local Variable - <returnType> (^<blockName>) (<parameterType>) =
Property - @property (nonatomic, copy) int(^equation) (int, int);
Parameter of a method (void)setEquation: (int(^) (int, int))
blockName;
Argument of a method [simpleOP setEquation:^int(int a, int b)
{return a+b;}];
Typical Use: Enable the caller to provide the callback code at the point
of invocation. Use in system framework APIs (completion handlers,
notification handlers, error handlers, enumeration, view animation
and transitions, sorting)
Chapter 2
XIB file an XML representation of the achieved objects.

Chapter 3
View and the view hierarchy
-Make up the user interface of an application.
Drawing
-Drawing operations performed on the CGContextRef must fall within
the bounds rectangle. Otherwise, they will be clipped to that rectangle
Core Graphics framework
-A C language API for 2D drawing
-The hub of the Core Graphics framework is CGContextRef:
-(void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];
CGContextSetLineWidth(ctx, 10); -> set up drawing state
CGContectSetRGBStrokeColor(ctx, 1, 0, 0, 1); -> set color
CGContextAddRect(ctxm bounds); -> added a path to the context
CGContextStrokePath(ctx);
->
perform
drawing
operation
}
Motion Event Methods For handling shakes, the methods toy
override in a UIResponder subclass are known as the motion event
methods
When a UIViewController is instatiated, it doesnt create or load its
view right away. Only when the view is moving to the screen will a
view controller bother to create its view.
View will be destroyed if system is running low memory or is not
current view in the screen.
To Avoid Memory leaks, the convention for IBOutets is to declare them
as weak references. One exception of this rule: Keep a strong
reference to top-level objects in a XIB file.
Segue is the transition from one scene to another within a storyboard
[self performSegueWithIdentifier:@ sender:self];

[segue.destinationViewController
performSelector:@selector(setLabelText:) withObect:@arrive from 1
Chapter 4
UITableView a table view for displaying and editing hierarchical lists
of information. Use UITableViewCell objects to draw the visible rows of
the table. Is made up of zero or more sections, each with its own rows.
UITableViewController
numberOfRowsInsection,
numberOfSectionsInTableView,
cellForRowAtIndexPath

NSKeyedArchiver Make a class able to encode data into binary data


(before writing to a binary file)
NSKeyedUnArchiver Make a class able to decode data into binary
data (before writing to a binary file)
Core Data can turn objective-c objects into data that is stored in a
SQLite database file and vice-versa. It gives us the ability to fetch and
store data in a relational datanase without having to know SQL.
Core Data Stack

UITableViewCellStyles

Role of Core Data

Chapter 5
UIWebView
NSURL * url = [NSURL URLWithString:urlString];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[self.detailViewController.webView loadRequest:request];
Hide the keyboard
-(IBAction)textFieldReturn:(id)sender{
[sender resignFirstResponder];}
Chapter 6

Step 1: Create an instance


Step 2: Configure its delegate
Step 3: Detect device capabilities + isSourceTypeAvailable
Step 4: Save Images/Movies
-Framework: UIKit/IKit.h
-An image -> UImageWriteToSavePhotoAlbum();
-A video -> UISaveVideoAtPathToSavedPhotoAlbum();
Step 5: Final call back method
-(void) imageLFInishedSavingWIthErrorContextInfo;
Play Video Record Notification A need of sending message from an
object to other objects that are interested in it. Instead of sending
messages to everybody, the object posts notifications to a notifications
center. Interested objects register to receive a message when a
particular notification is posted or when a particular object posts.
Universal Unique Identifiers Use the Cocoa Touch mechanism for
creating universally unique identifiers (UUIDs), also known as globally
unique identifiers (GUIDs). Objects of type CFUUIDRef represent a
UUID and are generated using the time, a counter, and a hardware
identifier, which is usually the MAC address of the Ethernet card.
Chapter 7
Web Service Require Server side, Exchange request, responses via
HTTP. Typically exchange in form of XML/JSON
JSON A text-based open standard designed for human readable data
interchange. Typically use in transition over the network. EX
{ Nina:{ mobile:02222, email:mail@hotmail.com} }
Chapter 8
Core data save to file system

NSFetchRequest- Get feedback fron NSManageObjectContext. After


fetchRequest executed, get an array of all the objects that match the
parameters of that request.
NSPredicate Only the object that satisfy the predicate are returned.
Chapter 9 Map
MKMapItem Specific point on a map name, etc
MKPlaceMark Placemark data address, coordinate, etc
Forward Geocoding
-Convert street address to lat long / can reverse (Reverse Geocoding)
-User CLGeocoder class to a text based address sting into a CLLocation
object. Geocoding as address.
Work with MKMapItem
-Initialize and open map with a given location
-Initialize a map with current location
-initialize a map with multiple locations

Web Service RSSReader


NSMutableArray * feeds = [[NSMutableArray alloc] init];
NSURL * url = [NSURL URLWithString:@www.google.co.th];
NSXMLParser
*
parser
=
[[NSXMLParser
alloc]
initWithContextsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
-(void) condigureView{
NSURL
*
myURL
=
[NSURL
URLWithString:[self.url
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:myURL];
[self.webView loadRequest:request];
JSON Serialization
Read Local File
-(NSData *)readLocalFile{
NSFileManager * fileMgr = [NSFileManager defaultManager];
NSBundle * mainBundle = [NSBundle mainBundle];
NSString * fileStr = [mainBundle pathForResource:@filename
ofType:@txt];
NSData * databuffer = nil;
If([fileMgr fileExistsAtPath:fileStr] == YES){
Databuffer * dataStr = [[NSString alloc] initWithData:dataBuffer
encoding:NSASCIIStringEncoding];
}
return dataBuffer;
}
Generate an Object from Json Data
-(NSMutableDictionary *) serializeJson:(NSData*)jsonStr
{
NSE * error;
NSMutableDictionary * allRecords = [NSJSONSerizlization
JSONObjectWithData: jsonStr
options:NSJSONReadingMutableContainers error:&error];
If(!error){
NSDictionary * record1 = allRecords[@record1];
NSLog(@phone = %@, [record1 objectForKey:mobile]);
}
return allRecord;
}
Invoke readLocalFile
NSData * jsonStr = [self readLocalFile];
If (jsonStr){
NSMutableDictionary * allRecords = [self serializeJson:JsonStr]; }
Write data to a file
-(void) writeFile:(NSData *)nsData{
NSFileManager * fileMgr = [NSFileManager defaultManager];
//Refer to a directory to write a file/read file
NSArray * dirPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * fileDir = dirPaths[0];
NSString * dataFile = [fileDir stringByAppendingString:@out.text];
//Write a file
[fileMgr createFileAtPath:dataFile contents:nsData attributes:nil];
}
Invoke Write File [continue from invoke read file]
NSERror * error;
NSData
*
nsData
=
[NSJSONSerialization:
dataWithJSONObject:allRecords options:NSJSONWritingPrettyPrinted
error:&error;
[self writeFile:nsData];
Add blue text into read local file, it will change to read from directory.
GeoName, Feeder Model
_feed = [[FeederModel alloc] initFromURLWithString:@www.a.co.th
completion:^(JSONModel *model, JSONModelError * err)
{
NSLog(@%@, _feed.geonames[0]);
[[self tableView] reloadData];
}];
CustomCell/ TableViewCell
TableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:
@CellIdentifier forIndexPath:indexPath];
Cell.textLabel = @text;
return cell;
Database
Create empty with coredata
Create storyboard and make asscociation
Import coredata library
Change appdelegate.h
Create UI Appdelegate.h
-Application: didFinishLaunchingWithOption:
{ //delete other statments
return YES;
}
Save Data
AppDelegate * appdelegate = [[UIApplication sharedAppication]
delegate];
NSManagedObjectedContext * context =
[appDelegate managedObjectContext];
NSManagedObject * newContact;
newContact = [NSEntityDescription
insertNewObjectForEntityForName:@Contacts
inManagedObjectContext:context];
[newContact setValue:_value forKey:@name];

NSErrpr *error;
[context save:&error];
Find Data
AppDelegate * appdelegate = [[UIApplication sharedAppication]
delegate];
NSManagedObjectedContext * context =
[appDelegate managedObjectContext];
NSEntityDescription * entityDesc = [NSEntityDescrption
entityForName:@Contacts inManagedObjectContext:context];
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate * pred = [NSPredicate predicateWithFormat:@(name
= %@), _name.text];
// LIKE %%;
[request setPredicate:pred];
NSError * error;
NSArray * objects = [context executeFetchRequest:request
error:&error];
If (object.count>0){
NSManagedObject *matches = _object[0];
}
Edit
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity: [NSEntityDescriotion entityForName:@Contatcs
inManagedbjectContext: context]];
NSError * error = nil;
NSArray * results = [context executeFetchRequest error:&error];
[context save:&error];
Delete
NSManagedObjectContext * context = [self.fetchResultsController
managedObjectContext];
NSManagedObjectContext * objectToBeDeleted = [self.
fetchResultsController objectAtIndexPath: indexPath];
[context deleteObjectLobjectToBeDeketed];
NSError = nil;
[context save:&error];
Photolot
-(void) addItemViewController: (AddViewController*)
controller(Photo*) item
{
Photo * op = [[Photo alloc] init];
op = item;
[_PhotoList insertObjectLop atIndex:[_PhotoList count]];
[_PhotoTable reloadData];
}
-(void)prepareForSegue: (UIStoryboardSegue*)segue sender:
(id)sender{
If ([[segue identifier] isEqualToString:@Detail])
{
DetailViewController * detailView = [segue
destinationCiewController];
NSIndexPath * myIndexPath = [selfTableView
indexPathForSelectedRow];
[detailView setOb:[_PhotoList objectAtIndex:tow];
} else if ([[segue identifier] isEqualToString:@NewPhoto]){
AddViewController * viewControllerB = [segue
destinationViewController];
viewControllerB.delegate = self;
}
}
-(void)tableView: (UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle) editingStyle forRowAtIndexPath:
(NSIndexPath *)indexPath
{
If(editingStyle == UITableViewCellEditingStyleDelete){
_indexPath = indexPath;
UIAlertView *alertView =
[[UIAlertView alloc]initWithTitle:@"Confirm Delete" message:@"You
sure to delete ? " delegate:self cancelButtonTitle:@"Yes"
otherButtonTitles:@"No", nil];
[alertView show];
}
}
-(void)DeleteRow: (NSIndexPath*) indexPath
{
[_PhotoList removeObjectAtIndex:indexPath.row;
[_PhotoTable deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation: UITableViewRowAnimationAutomatic];
}
-(void)alertView: (UIAlertView*)alertView clickedButtonAtIndex:
(NSInteger) buttonIndex
{
If (buttonIndex == 0)
{ selfDeleteRowL_indexPath};
}
}
Map
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <AddressBook/AddressBook.h>
CLLocationCoordinate2D coords;
-(IBAction)getDirections:(id)sender
{
CLGeocoder * geocoder = [[CLGeocoder alloc] init];
NSString * addressStr = [NSString stringWithFormat:@%@ %@ %@
%@, _address.text, _city.text, _state.text, _zip.text];

Geocoder geocoderAddressString:addressStr completionHandler:^


(NSArray * placemarks, NSError)
{
If(!error) {
If(placemarks && placemarks.count > 0) {
CLPlacemark * placemark = placemarks[0];
CLLocation * loc = placemark.location;
_coords = loc.coordinate;
[self showMap];
}}}
-(void)showMap
{
NSDictionary * address = @{
(NSString *) kABPersonAddressStreetKey: _address.text};
MKPlacemark * place = [[MKPlacemark alloc]
initWithCoordinate:_coords addressDictionary:address];
MKMapItem * mapItem = [[MKMapItem alloc]
initWithPlaceMark:place];
NSDictionary * options =
@{MKLaunchOptionsDirectionsModKey:MKLaunchOptionsDirections
ModeDriving};
[mapItem openInMapsWithLaunchOptions:options];
}
CLLocationManager
_locationManager = [[CLLocationManager alloc] init];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
_startLocation = nil;
-(void)locationManager:(CLLocationManager*)manager
didUpdateLocations:(NSArray*)locations
{
CLLocation * loc = (CLLocation*) [locations lastObject];
If(_startLocation == nil) {
_startLocation = loc;
}
CLLocationDistance distanceBetween = [loc distanceFromLocation:
_startLocation];
_mapView.showUserlocation = YES;
_mapView.mapType = MKMapTypeSatellite;
_mapView.mapType = MKMapTypeStandard;
_mapView.centerCoordinate = userLocation.location.coordinate;
Search
[_maoView removeAnnotations:[_mapView annotations]];
-(void)performSearch {
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc]init];
Request.naturalLanguageQuery = @search text;
Request.region = _mapView.region;
_martchingItems = [[NSMutableArray alloc] init];
MKLocalSearch * search = [[MKLocalSearch alloc]
initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse *
response, NSError * error)
{
If (response.mapItems.count > 0)
{
For (MKMapItem * item in response.mapItems) {
[_matchinfItems addObject:item];
MKPointAnnotation * annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = item.placemarl.coordinate;
annotation.title = item.name;
[_mapView addAnnotation:annotation];
}
}

Core Location Framework


CLLocation Manager Retrieve the most recent location and heading
data. Track large or small changes in the user current location. Report
heading changes from the onboard compass. Monitor distinct regions
of interest and generating location events when the user enters or
leaves those region.
CLLocation Represent the location data generated by a
CLLocationManager object. Store the geographical coordinates,
altitude, measurement accuracy, the speed heading.
Mapkit FrameWork
MKMapView Is a subclass of UIView. Present information in map.
Satellite or hybrid. Include support for adding annotation to a map
MKMapViewDelegate protocol Receive notification of events relating
to the map view.
Map Regions
Region = Displayed area of the map
-Center location (lat + long)
-Span of the surrounding area by distance and coordinate based
degree
Key SQLite Functions
-sqlite3_open() open specified database file.
-sqlite3_close() close a previously opened database file.
-sqlite3_prepare_v2() prepare a SQL statement ready for execution.
-sqlite3_step() execute a SQL statement previously prepared by
sqlite3_prepare_v2().
-sqlite3_column_<type> () return a data field from results of a SQL
Retrieval operation.
-sqlite3_finalize() delete a previously prepared SQL statement from
memory.
-sqlite3_exec() combine the function of sqlite3_prepare_v2(),
sqlite3_step() and sqlite3_finalize() into a single function call.

Potrebbero piacerti anche