#CS193P#
##Lecture01##
- URLs
##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
- Encapsulation
-
Selectors identify methods by name
- A selector has type SEL
SEL action = [ button action ]; [ button setAction:@selector(start:) ];
- A selector has type SEL
-
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*/ }
- You can ask an object about its class
-
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
- Value and collection classes
-
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!!!
- Common NSArray methods
-
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
- Two step process
##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.
+ allocand- copycreate objects with retain count == 1- retainincrements retain count- releasedecrements retain count- when retain count reaches 0,object is destoryed
- deallocmethod invoked automatically!!!- One-Way street,once you're in
-deallocthere's no turning back
- dealloc
- (void) dealloc { /* do any cleanup that's necessary */.../*when we're done,call super to clean up*/ [ super dealloc ]; }
- Every object has a retain count
-
Object Lifecycle Recap
- Objects begin with a retain count of 1
- Increase and decrease with
-retainand-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
- Exception is calling
-
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,newreturn a retained object that thecaller needs to release.方法名中包含alloc,copy,new的方法通常会返回一个非autorelease的对象,需要你负责减少retain count,自行释放内存. All other methods return autoreleased objects.
- Methods whose names include
-
NSMutableString *string = [ [ NSMutableString alloc ] init ];
// we are responsible for calling ``-release`` or ``-autorelease``
[ string autorelease ];
-
How does
-autoreleasework?- Object is added to current autorelease pool
- Autorelease pools track objects scheduled to be released
- when the pool itself is released,it sends
-releaseto all its objects. [ pool drain ]会逐个检查池内的对象,在所有对象上调用release方法,有的对象此时就自动调用了dealloc方法,有的对象还未到调用dealloc的时候。
- when the pool itself is released,it sends
- 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
- Many methods return autoreleased objedcts
-
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方法中使用,否则会造成无限循环。
- Memory management policies(only for object properties)
@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 .
- singleton design pattern
-
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
- Property List(often XML),describing your application
-
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
- Property List(often xml),describing your application
- vim有12个粘贴板,分别是0、1、2、...、9、a、“、+;用:reg命令可以查看各个粘贴板里的内容。在vim中简单用y只是复制到“(双引号)粘贴板里,同样用p粘贴的也是这个粘贴板里的内容;
- 要将vim的内容复制到某个粘贴板,需要退出编辑模式,进入正常模式后,选择要复制的内容,然后按"Ny完成复制,其中N为粘贴板号(注意是按一下双引号 然后按粘贴板号最后按y),例如要把内容复制到粘贴板a,选中内容后按"ay就可以了,有两点需要说明一下:
- “号粘贴板(临时粘贴板)比较特殊,直接按y就复制到这个粘贴板中了,直接按p就粘贴这个粘贴板中的内容;
- +号粘贴板是系统粘贴板,用"+y将内容复制到该粘贴板后可以使用Ctrl+V将其粘贴到其他文档(如firefox、gedit)中,同理,要把在其他地方用Ctrl+C或右键复制的内容复制到vim中,需要在正常模式下按"+p;
- 要将vim某个粘贴板里的内容粘贴进来,需要退出编辑模式,在正常模式按"Np,其中N为粘贴板号,如上所述,可以按"5p将5号粘贴板里的内容粘贴进来,也可以按"+p将系统全局粘贴板里的内容粘贴进来。