Skip to content

Instantly share code, notes, and snippets.

@flyfire
Created October 5, 2013 15:57
Show Gist options
  • Select an option

  • Save flyfire/6842625 to your computer and use it in GitHub Desktop.

Select an option

Save flyfire/6842625 to your computer and use it in GitHub Desktop.

#CS193P#

##Lecture01##

##Lecture02##

  • OOP Vocabulary

    • Encapsulation Keep implementation private and separate from interface
    • Polymorphism Different objects,Same interface
    • Inheritance Hierarchical organization,Share Code,Customize or extend behaviors
  • Selectors identify methods by name

    • A selector has type SEL SEL action = [ button action ]; [ button setAction:@selector(start:) ];
  • Conceptually similar to function pointer

  • Selectors include the name and all colons -(void) setName:(NSString *)name age:(int)age; SEL sel = @selector(setName:age:);

  • Working with selectors

    • You can determine if an object responds to a given selector id obj;SEL sel = @selector(start:);if ( [obj respondsToSelector:sel] ) {[obj performSelector: sel withObject:self];}

    • This sort of introspection and dynamic messaging underlies many cocoa design patterns -(void) setTarget:(id) target; -(void) setAction:(SEL)action;

  • Class Introspection

    • You can ask 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*/ }
  • vararg可变参数

    • vararg functions argument
  • Foundation Framework

    • Value and collection classes
      • numbers,arrays,sets,dictionaries
    • User defaults
      • preferences
    • Archiving
      • all of the foundation objects,the arrays,the sets,the dictionaries know how to archive themselves so they can basically flatten themselves down to data to be written out to disk or stored in any way.And then they also know how to unarchive themselves.So after they've been saved at the disk,the next time you run your program,they can unarchive and just expand back out into an entire object graph again.
    • Notifications
      • basically ways that objects can send out a notification that they're dong something interesting that other objects might want to know about without those two objects actually having pointers.
    • Undo manager
    • Tasks,timers,threads
    • File System,pipes,I/O,bundles
  • NSObject

    • Root Class
    • Implements many basics
      • Memory management
      • Introspection
      • Object equality
  • NSString

    • 字符串中不包含数字,intvalue返回0,如果开头有数字,如449a5999,返回第一个数字,也就是449。
    • NSMutableString subclasses NSString,allow a string to be modified.
      • +(id) string;
      • -(void) appendString:(NSString*) string;
      • -(void) appendFormat:(NSString*) format,...
  • NSArray

    • Common NSArray methods
        • arrayWithObjects:(id) firstObj,...;//nil terminated!!!
        • (unsigned) count;
        • (id) objectAtIndex:(unsigned) index;
        • (unsigned) indexOfObject:(id) object;
    • NSNotFound returned for index if not found
    • Be careful of the nil termination!!!
  • Object Creation

    • Two step process
      • allocate memory to store the object
      • initialize object state
      • alloc
      • class method that knows how much memory is needed
      • init
      • instance method to set initial values,perform other setup

##Lectore03##

  • Memory Management || 内存管理 || Allocation || Destruction || || C || malloc || free || || Objective-C || alloc || dealloc ||

  • Reference Counting

    • Every object has a retain count
      • Defined on NSObject.
      • As long as retain count > 0,object is alive and valid.
    • + alloc and - copy create objects with retain count == 1
    • - retain increments retain count
    • - release decrements retain count
    • when retain count reaches 0,object is destoryed
      • - dealloc method invoked automatically!!!
      • One-Way street,once you're in -dealloc there's no turning back
    • dealloc - (void) dealloc { /* do any cleanup that's necessary */.../*when we're done,call super to clean up*/ [ super dealloc ]; }
  • Object Lifecycle Recap

    • Objects begin with a retain count of 1
    • Increase and decrease with -retain and -release
    • When retain count reaches 0,object deallocated automatically
    • You never call dealloc explicitly in your code
      • Exception is calling -[ super dealloc ]
      • You only deal with alloc,copy,retain,release
  • Object Ownership

- (void) setName:(NSString *)newName{
    if  ( name != newName ) {
        [ name release ];
        name = [ newName retain ]; //name = [ newName copy ];
        // name has retain count of 1,we own it
    }
}
- (void) dealloc {
    //do any cleanup that's necessary
    [ name release ];
    //when we're done,call super to clean up
    [ super dealloc ];
}
  • Autoreleasing Objects
    • Calling - autorelease flags an object to be sent release at some point in the future

    • Let you fulfill your retain/release obligations while allowing an object some additional time to live

    • Makes it much more convenient to manage memory

    • Very useful in methods which return a newly created object

    • Method Names & Autorelease

      • Methods whose names include alloc,copy,new return a retained object that the caller needs to release.方法名中包含alloc,copy,new的方法通常会返回一个非autorelease的对象,需要你负责减少retain count,自行释放内存. All other methods return autoreleased objects.
NSMutableString *string = [ [ NSMutableString alloc ] init ];
// we are responsible for calling ``-release`` or ``-autorelease``
[ string autorelease ];
  • How does -autorelease work?

    • Object is added to current autorelease pool
    • Autorelease pools track objects scheduled to be released
      • when the pool itself is released,it sends -release to all its objects.
      • [ pool drain ]会逐个检查池内的对象,在所有对象上调用release方法,有的对象此时就自动调用了dealloc方法,有的对象还未到调用dealloc的时候。
    • UIKit automatically wraps a pool around every event dispatch.
  • Hanging onto an autoreleased objecct

    • Many methods return autoreleased objedcts
      • Remember the naming conventiosns...
      • They're hanging out in the pool and will get released later
    • If you need to hold onto those objects you need to retain them
      • Bumps up the retain count before the release happens
  • Properites

    • Provide access to object attributes
    • Shortcut to implementing getter/setter methods
    • Also allow you to specify:
      • read-only versus read-write access
      • memory management policy
//method declarations
- (NSString *)name;{
    return name;
}
- (void) setName:(NSString *)value;{
    if (value != name ){
        [name release];
        name = [ value copy ];
    }
}
- (int) age;{
    return age;
}
- (void) setAge:(int) value;{
    age = value;
}
- (BOOL) canLegallyVote;{
    return ([self age] > 17);
}
//property declarations
@property int age;
@property (copy) NSString *name;
@property (readonly) BOOL canLegallyVote;
@synthesize age;
@synthesize name;
-(BOOL) canLegallyVote{
    return (age > 17);
}
  • Property Attributes
    • Memory management policies(only for object properties)
      • @property (assign) NSString *name; //pointer assignment Assign的意思是当它创建setter时,他不会保持新的对象,他不会释放旧的对象,他只会分配它。it will not retain the new object,it's not going to release the old object,it just going to assign.
      • @property (retain) NSString *name; //retain called,释放旧的对象,保持新的对象。release the old object and retain the new.
      • @property (copy) NSString *name; // copy called,释放旧的对象,复制新的对象。release the old object and copy the new.
      • readonly表明只会生成getter,不会生成setter。
      • self.age=newAge;实际上调用的是setAge方法。不要在setAge方法中使用,否则会造成无限循环。
@interface Person:NSObject{
    int numberOfYearsOld;
}
@property int age;
@end
@implementation Person
@synthesize age=numberOfYeadsOld;
@end

##Lecture04##

  • AppLifecycle
    • 应用来自UIKit,叫做UIApplication类,your application comes from UIKit,It's called the UIApplication class,and that's what get started when your app is initialized.
    • UIApplication is a Singleton design pattern,which means when you run your application there is only one instance of UIApplication and you can always get to it from anywhere in your application.If you need to get to your application instance,you can always get to it with this class method called sharedApplication.[ UIApplication sharedApplication ] you can get to the object that represents your app.And there's several things you can query it for,but it's more interesting for how it calls you back.
Launch app -->App initialized -->Load main nib==>Handle event -->Exit app
  • UIKit Framework

    • starts your application
    • Every application has a single instance of UIApplication
      • singleton design pattern @interface UIApplication - (UIApplication *)sharedApplication @end
      • Orchestrates <聚合>the lifecycle of an application
      • Dispatches events
      • Manages status bar,application icon badge
      • Rarely subclassed,uses delegation instead
      • Delegation is a way for you to keep the UIApplication or other objects,but in this case UIApplication object intact. you're not going to change it,override it,but to still get some of the notifications and messages that are important for your application execution.Delegation allows for an object or a class to have very contained behavior and to provide hooks to someone else for customization .
  • Delegation

    • Control passed to delegate objects to perform application-specific behavior
    • Avoids need to subclass complex objects
    • Many UIKit classes use delegates:UIApplication,UITableView,UITextField
  • Info.plist file

    • Property List(often XML),describing your application
      • Icon Appearance
      • Status bar style(default,black,hidden)
      • Orientation<方向,定位>
      • Uses wifi networking
      • system requirements
      • can edit most properties in XCode
  • MVC

    • Model-View-Controller basically says that there are three distinct responsibilities for your application.
    • The view,which is what you present to the user.
    • The model,which is the storage of data or the representation of data inside your app.
    • The controller manages taking the data and presenting that to the view.And similarly,when the view wants to manipulate the data,it's the conduit with which the view can do that.<如果视图想要操作数据,controller会是视图可以这样做的管道。>
    • The fundamental premise here is that the view and model should never know about each other or talk to each other.The controller is the intermediary that manages presentation and control.<controller 是管理演示和控制的媒介>
  • Model

    • Manages the app data and state
    • Not concerned with UI or presentation
    • Often persists somewhere
    • Same model should be reusable,unchanged in different interfaces.
      • Model is the app data and the state of the app,could be a database,
  • View

    • Present the Model to the user in an appropriate interface
    • Allow user to manipulate<操作>data
    • Does not store any data(except to cache state)
    • Easily reusable & configurable to display different data
    • Nib Fies help you design view,layout user interface elements,add controller objects,connect the controller and UI
  • Controller

    • Intermediary between Model & View
    • Updates the view when the model changes
    • Updates the model when the user manipulates the view
    • Typically where the app logic lives.
  • Info.plist

    • Property List(often xml),describing your application
      • Icon appearance
      • Status bar style(default,black,hidden)
      • Orientation
      • Uses Wifi networking
      • System Requirements
    • Can edit most properties in XCode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment