文章目錄
- NSStringNSMutableString
- Date Times
- NSArrayNSMutableArrayDictionary
- NSNotification
- Event response
- MVC
- Delegate
- Target-Action
- Categories
- Singletons
Cocoa中常用的類NSStringNSMutableString
賦值 |
NSString *myString = @"some string"; NSString *myString = [NSStringstringWithFormat:@"object = %@",someObject]; |
轉換 |
NSString *upper = [myStringuppercaseString]; intintString = [myStringintValue]; |
去內容 |
NSString *trimmed = [myString string ByTrimmingCharactersInSet: [NSCharacterSet whitespace CharacterSet]]; |
截取字串 |
NSString *aString = [numberStringsubstringToIndex:3]; NSRange range = NSMakeRange(4,3); NSString *aString = [numberStringsubstringWithRange:range]; NSArray *arr = [numberString componentsSeparatedByString: @" "]; |
替換 |
NSString *aString = [numberStringstringByReplacingOccurrencesOf String:@"three" withString: @"four"]; |
尋找 |
NSRangefoundRange = [numberStringrangeOfString:@"two"]; BOOL found = ([numberStringrangeOfString:@"two"].location != NSNotFound); |
檔案 |
NSString *fileContents = [NSStringstringWithContentsOfFile: @"myfile.txt"]; NSURL *url = [NSURL URLWithString: @"http://google.com"]; NSString *pageContents = [NSStringstringWithContentsOfURL:url]; |
Date Times
NSDate *myDate = [NSDate date];
NSTimeIntervalsecondsPerDay = 24*60*60;
NSDate *now = [NSDate date];
NSDate *yesterday = [now addTimeInterval:-secondsPerDay];
NSDateComponents *comp = [[NSDateCo m ponentsalloc] init];
[co m p setMonth:06];
[co m p setDay:01];
[co m p setYear:2010];
NSCalendar *myCal= [[NSCalendaralloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDate *myDate= [myCaldateFromComponents:comp];
NSArrayNSMutableArrayDictionary
NSString *string1 = @"one";
NSString *string2 = @"two";
NSString *string3 = @"three";
NSArray *myArray = [NSArrayarrayWithObjects:string1, string2, string3, nil];
for (NSString *obj in myArray) {
NSLog(@"%@",obj);
}
for (NSString *obj in [myArrayreverseObjectEnumerator])
{
NSLog(@"%@",obj);
}
NSArray *arr1 = [NSArrayarrayWith Objects:@"iPhone", @"iPod",nil];
NSDictionary *myDict = [[NSDictionar y alloc] dictionaryWithObjectsAndKeys: arr1, @"mobile", arr2, @"computers", nil];
for (id key in myDict) {
NSLog(@"key: %@, value: %@",
key, [myDictobjectForKey:
key]);
}
[myDict setObject:string2 forKey:@"media"];
NSNotification
Notifications provide a handy way for youto pass information between objects in your application without needing a direct reference between them. which contains a name, an object (often the object posting the notification), and an optional dictionary.
登記訊息、訊息處理方法、登出
[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(doSomething:)
name:@"myNotification"
object:nil];
-(void)deallc
{
[[NSNotificationCenterdefaultCenter] removeObserver:self];
[superdealloc];
}
-(void)doSomething:(NSNotification*)aNote
{
NSDictionary *myDict = [aNoteobject];
NSLog(@”%@”, myDict);
}
發送訊息
[[NSNotificationCenterdefaultCenter] postNotificationName:MY_NOTIFICATIONobject:myDict];
記憶體管理
iOS不支援GC,因此必須手動釋放建立的對象[注意是建立者負責釋放,像Factory 方法的對象不需要調用者釋放]
[object release];
Remember this basic rule of thumb: Any time you call the alloc, copy, or retainmethods on an object, you must at some point later call the release method.
THE AUTORELEASE ALTERNATIVE
If you’re responsible for the creation of an object and you’re going to pass it off to some other class for usage, you should autorelease the object before you send it off.
This is done with the autorelease method:
[objectautorelease];
You’ll typically send the autorelease message just before you return the object at the end of a method. After an object has been autoreleased, it’s watched over by a special NSAutoreleasePool. The object is kept alive for the scope of the method to which it’s been passed, and then the NSAutoreleasePool cleans it up.
-(NSString *)makeUserName
{
NSString *name = [[NSStringalloc] initWithString:@”new name”];
return [name autorelease];
}
如上例,返回的對象由NSAutoreleasePool負責釋放,缺點是釋放時刻不確定,沒釋放前佔用系統的記憶體,調用者不用處理釋放的問題,不過在使用retain方法時,必須調用配對的release,以平衡引用計數
使用UIKit庫一個例子
UIButton *myButton = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
In most cases, the Cocoa Touch frameworks use a naming convention to help you decide when you need to release objects: If the method name starts with the word alloc, new, or copy, then you should call releasewhen you are finished with the object.
RETAINING AND COUNTING
What if you want to hold onto an object that has been passed to you and that will be autoreleased? In that case, you send it a retain message:
[object retain];
When you do this, you’re saying you want the object to stay around, but now you’ve become responsible for its memory as well: you must send a release message at some point to balance your retain.
Event response
bare events (or actions)
delegated events
notification
圖書 iPhone and iPad in Action Chapter6 有詳細的說明
設計模式MVC
The Model View Controller (MVC) pattern separates an application’s data structures (the model) from its user interface (the view),with a middle layer (the controller) providingthe “glue” between the two. The controller takes input from the user (via the view), determines what action needs to be performed, and passes this to the model for processing. The controller can also act the otherway: passing information from the model to the view to update the user interface.
Delegate
The Delegate pattern is useful as an alternative to subclassing, allowing an object to define a method but assign responsibility for implementing that method to a different object (referred to as the delegate objector, more commonly, the delegate).
Delegates need not implement all (or even any) of the delegate methods for the source object. In that case, the source object’s default behavior for the method is often used.
下例通過委託改變了控制項的行為[鍵盤不顯示]
-(BOOL) textFieldShouldBeginEditing: (UITextField *)textField
{
return NO;
}
-(void)viewDidLoad {
CGRectrect = CGRectMake(10,10, 100,44);
UITextFiled *myTextField=[[UITextFieldalloc] initWithFrame:rect];
myTextField.delegate = self;
[self.viewaddSubView:myTextField];
[myTextField release];
}
Target-Action
下例展現了一個按鈕的響應處理
-(void) buttonTap: (id)sender
{
NSLog(@”Button tapped”);
}
-(void)viewDidLoad{
….
[myButton addTerget:self action:@selector(buttonTap:) forControlEvents: UIControlEventTouchUpInside];
…
}
Categories
Like delegates, categories provide an alternative to subclassing, allowing you to add new methods to an existing class. The methods then become part of the class definition and are available to all instances (and subclasses) of that class.
上例給類UIImage增加了一個擴充的方法,這樣調用者都可以調用這個方法,相比繼承形式更輕量
Singletons
單一實例,Cocoa中有很多的這個模式
如
float level = [[UIDevicecurrentDevice] batteryLevel];
…
程式生命期