UITextView控件的詳細講解
感覺寫的相當不錯,而且很全就直接轉載了
1.建立并初始化
建立UITextView的檔案,并在.h檔案中寫入如下代碼:
#import <UIKit/UIKit.h>
@interface TextViewController : UIViewController <UITextViewDelegate>
{
UITextView *textView;
}
@property (nonatomic, retain) UITextView *textView;
@end
在.m檔案中初始化這個textview,寫入代碼如下:
self.textView = [[[UITextView alloc] initWithFrame:self.view.frame]autorelease]; //初始化大小并自動釋放
self.textView.textColor = [UIColor blackColor];//設定textview裡面的字型顔色
self.textView.font = [UIFont fontWithName:@"Arial" size:18.0];//設定字型名字和字型大小
self.textView.delegate = self;//設定它的委托方法
self.textView.backgroundColor = [UIColor whiteColor];//設定它的背景顔色
self.textView.text = @"Now is the time for all good developers tocome to serve their country.\n\nNow is the time for all good developers to cometo serve their country.";//設定它顯示的内容
self.textView.returnKeyType = UIReturnKeyDefault;//傳回鍵的類型
self.textView.keyboardType = UIKeyboardTypeDefault;//鍵盤類型
self.textView.scrollEnabled = YES;//是否可以拖動
self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适應高度
[self.view addSubview: self.textView];//加入到整個頁面中
2. UITextView退出鍵盤的幾種方式
因為你點選UITextView會出現鍵盤,如果你退出鍵盤,有如下幾種方式:
(1)如果你程式是有導覽列的,可以在導覽列上面加多一個Done的按鈕,用來退出鍵盤,當然要先實UITextViewDelegate。
代碼如下:
- (void)textViewDidBeginEditing:(UITextView *)textView {
UIBarButtonItem *done = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(leaveEditMode)] autorelease];
self.navigationItem.rightBarButtonItem = done;
}
- (void)textViewDidEndEditing:(UITextView *)textView {
self.navigationItem.rightBarButtonItem = nil;
}
- (void)leaveEditMode {
[self.textView resignFirstResponder];
}
(2)如果你的textview裡不用Enter鍵,可以把Enter鍵當做退出鍵盤的響應鍵。
代碼如下:
#pragma mark - UITextView Delegate Methods
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
這樣無論你是使用電腦鍵盤上的Enter鍵還是使用彈出鍵盤裡的return鍵都可以達到退出鍵盤的效果。
(3)還有你也可以自定義其他加載鍵盤上面用來退出,比如在彈出的鍵盤上面加一個view來放置退出鍵盤的Done按鈕。
代碼如下:
UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
[topView setBarStyle:UIBarStyleBlack];
UIBarButtonItem * helloButton = [[UIBarButtonItem alloc]initWithTitle:@"Hello" style:UIBarButtonItemStyleBordered target:self action:nil];
UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
NSArray * buttonsArray = [NSArray arrayWithObjects:helloButton,btnSpace,doneButton,nil];
[doneButton release];
[btnSpace release];
[helloButton release];
[topView setItems:buttonsArray];
[tvTextView setInputAccessoryView:topView];
-(IBAction)dismissKeyBoard
{
[tvTextView resignFirstResponder];
}
(4)設定UITextView圓角問題
做法是在#import QuartzCore/QuartzCore.h 後,便能調用[textView.layer setCornerRadius:10]; 來把UITextView 設定圓角
(5)UITextView根據文本大小自适應高度
通過實作文本字數來确定高度,如下:
NSString * desc = @"Description it is a test font, and don't become angry for which i use to do here.Now here is a very nice party from american or not!";
CGSize size = [desc sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(240, 2000) lineBreakMode:UILineBreakModeWordWrap];
隻有UILabel需要定義的numberoflines為0,即不做行數的限制。如下:
[label setNumberOfLines:0];
[label setFrame:CGRectMake(40, 135, 240, size.height+10)];
[label setText:desc];
(6)UITextView自定選擇文字後的菜單
在ViewDidLoad中加入:
UIMenuItem *menuItem = [[UIMenuItem alloc]initWithTitle:@"分享到新浪微網誌" action:@selector(changeColor:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObject:menuItem]];
[menuItem release];
當然上面那個@selector裡面的changeColor方法還是自己寫吧,也就是說點選了我們自定義的菜單項後會觸發的方法。
然後還得在代碼裡加上一個方法:
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if(action [email protected](changeColor:))
{
if(textView.selectedRange.length>0)
return YES;
}
return NO;
}
今天的UITextView就講到這裡,主要講了UITextView的初始化和開發中會遇到的一些問題和自定義等問題。謝謝大家支援哈。
posted @ 2012-01-31 19:09 SuperHappy 閱讀(66) 評論(0) 編輯 UILabel的常見用法
- (void)loadView
{
[super loadView];
//1.UILable的大小自适應執行個體:
UILabel *myLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 2, 2)];//設定位置與大小
[myLabel setFont:[UIFont fontWithName:@"Helvetica" size:20.0]];//格式
[myLabel setNumberOfLines:0];//行數,隻有設為0才可以自适應
[myLabel setBackgroundColor:[UIColor clearColor]];//背景色
myLabel.shadowColor = [UIColor darkGrayColor];//陰影顔色
myLabel.shadowOffset = CGSizeMake(1.0,1.0);//陰影大小
NSString *text = @"abcdefghigklmnopqrstuvwxyz";
UIFont *font = [UIFont fontWithName:@"Helvetica" size:20.0];
CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(175.0f, 2000.0f) lineBreakMode:UILineBreakModeWordWrap];
CGRect rect=myLabel.frame;
rect.size=size;
[myLabel setFrame:rect];
[myLabel setText:text];
myLabel.shadowColor = [UIColor darkGrayColor];//陰影顔色
myLabel.shadowOffset = CGSizeMake(2.0,2.0);//陰影大小
[self.view addSubview:myLabel];
[myLabel release];
//2.UILable的基本用法擷取自饅頭MAN百度空間,感謝饅頭MAN
//空間位址:http://hi.baidu.com/bunsman/blog/item/95777b0ebacf05fe36d122e2.html
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 40.0, 200.0, 30.0)];
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 80.0, 200.0, 50.0)];
UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 140.0, 200.0, 50.0)];
UILabel *label4 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 200.0, 200.0, 50.0)];
UILabel *label5 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 260.0, 200.0, 50.0)];
UILabel *label6 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 320.0, 200.0, 50.0)];
UILabel *label7 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 380.0, 200.0, 50.0)];
//設定顯示文字
label1.text = @"label1";
label2.text = @"label2";
label3.text = @"label3--label3--label3--label3--label3--label3--label3--label3--label3--label3--label3--11個";
label4.text = @"label4--label4--label4--label4--4個";
label5.text = @"label5--label5--label5--label5--label5--label5--6個";
label6.text = @"label6";
label7.text = @"label7";
//設定字型:粗體,正常的是 SystemFontOfSize
label1.font = [UIFont boldSystemFontOfSize:20];
//設定文字顔色
label1.textColor = [UIColor orangeColor];
label2.textColor = [UIColor purpleColor];
//設定背景顔色
label1.backgroundColor = [UIColor clearColor];
label2.backgroundColor = [UIColor colorWithRed:0.5f green:30/255.0f blue:0.3f alpha:0.5f];
//設定文字位置
label1.textAlignment = UITextAlignmentRight;
label2.textAlignment = UITextAlignmentCenter;
//設定字型大小适應label寬度
label4.adjustsFontSizeToFitWidth = YES;
//設定label的行數
label5.numberOfLines = 2;
//設定高亮
label6.highlighted = YES;
label6.highlightedTextColor = [UIColor orangeColor];
//設定陰影
label7.shadowColor = [UIColor redColor];
label7.shadowOffset = CGSizeMake(1.0,1.0);
//設定是否能與使用者進行互動
label7.userInteractionEnabled = YES;
//設定label中的文字是否可變,預設值是YES
label3.enabled = NO;
//設定文字過長時的顯示格式
label3.lineBreakMode = UILineBreakModeMiddleTruncation;//截去中間
// typedef enum {
// UILineBreakModeWordWrap = 0,
// UILineBreakModeCharacterWrap,
// UILineBreakModeClip,//截去多餘部分
// UILineBreakModeHeadTruncation,//截去頭部
// UILineBreakModeTailTruncation,//截去尾部
// UILineBreakModeMiddleTruncation,//截去中間
// } UILineBreakMode;
//如果adjustsFontSizeToFitWidth屬性設定為YES,這個屬性就來控制文本基線的行為
label4.baselineAdjustment = UIBaselineAdjustmentNone;
// typedef enum {
// UIBaselineAdjustmentAlignBaselines,
// UIBaselineAdjustmentAlignCenters,
// UIBaselineAdjustmentNone,
// } UIBaselineAdjustment;
[self.view addSubview:label1];
[self.view addSubview:label2];
[self.view addSubview:label3];
[self.view addSubview:label4];
[self.view addSubview:label5];
[self.view addSubview:label6];
[self.view addSubview:label7];
[label1 release];
[label2 release];
[label3 release];
[label4 release];
[label5 release];
[label6 release];
[label7 release];
}
posted @ 2012-01-31 18:50 SuperHappy 閱讀(212) 評論(0) 編輯 視窗,視圖,視圖控制器和UIKit基礎
1、視窗:UIWindow
iPhone的規則是一個視窗,多個視圖,視窗是你在app顯示出來你看到的最底層,他是固定不變的,基本上可以不怎麼理會,但要知道每層是怎樣的架構。
2、視圖:UIView
UIView是使用者建構界面的基礎,所有的控件都是在這個頁面上畫出來的,你可以把它當成是一個畫布,你可以通過UIView增加控件,并利用控件和使用者進行互動和傳遞資料。
視窗和視圖是最基本的類,建立任何類型的使用者界面都要用到。視窗表示螢幕上的一個幾何區域,而視圖類則用其自身的功能畫出不同的控件,如導航欄,按鈕都是附着視圖類之上的,而一個視圖則連結到一個視窗。
3、視圖控制器:UIViewController
視圖控制器UIViewController,你可以把他當成是對你要用到視圖UIView進行管理和控制,你可以在這個UIViewController控制你要顯示的是哪個具體的UIView。另外,視圖控制器還增添了額外的功能,比如内建的旋轉螢幕,轉場動畫以及對觸摸等事件的支援。
4、 UIKit簡介
(1)顯示資料的視圖
UITextView:将文本段落呈現給使用者,并允許使用者使用鍵盤輸入自己的文本。

UILabel:實作短的隻讀文本,可以通過設定視圖屬性為标簽選擇顔色,字型和字号等。
UIImageView:可以通過UIImage加載圖檔賦給UIImageView,加載後你可以指定顯示的位置和大小。
UIWebView:可以提供顯示HTML.PDF等其他進階的Web内容。包括xls,word等文檔等。
MKMapView:可以通過MKMapView向應用嵌入地圖。很熱門的LBS應用就是基于這個來做的。還可以結合MKAnnotationView和MKPinAnnotationView類自定義注釋資訊注釋地圖。
UIScrollView:一般用來呈現比正常的程式視窗大的一些内容。可以通過水準和豎直滾動來檢視全部的内容,并且支援縮放功能。
(2) 做出選擇的視圖
UIAlertView:通過警告視圖讓使用者選擇或者向使用者顯示文本。
UIActionSheet:類似UIAlertView,但當選項比較多的時候可以操作表單,它提供從螢幕底部向上滾動的菜單。
(3)其他
UIBuuton:主要是我們平常觸摸的按鈕,觸發時可以調用我們想要執行的方法。
UISegmentControl:選擇按鈕,可以設定多個選擇項,觸發相應的項調用不同的方法。
UISwitch:開關按鈕,可以選擇開或者關。
UISlideer:滑動按鈕,常用在控制音量等。
UITextField:顯示文本段,顯示所給的文本。
UITableView:表格視圖,可以定義你要的表格視圖,表格頭和表格行都可以自定義,自定義的一個表格如下圖:
UIPickerView:選擇條,一般用于日期的選擇。
UISearchBar:搜尋條,一般用于查找的功能。
UIToolBar:工具欄:一般用于首頁面的架構。
UIActivityIndicatorView:進度條,一般用于顯示下載下傳進度。
UIProgressView:進度條,一般用于顯示下載下傳的進度條。
今天就簡單的介紹了一下IOS應用開發常用的一些控件,還有基礎的UIView,UIWindow和UIViewControl之間的關系,這些是基礎,直接影響到以後開發的能力,接下來我将分開講這些控件。
對于Button的圓角顯示,利用layer實作
示例:
對button1的邊框進行設定
#import <QuartzCore/QuartzCore.h>//不要忘記添加庫檔案
CALayer *layer1=[button1 layer];
//是否設定邊框以及是否可見
[layer1 setMasksToBounds:YES];
//設定邊框圓角的弧度
[layer1 setCornerRadius:15.0];
//設定邊框線的寬
[layer1 setBorderWidth:2.0];
//設定邊框線的顔色
[layer1 setBorderColor:[[UIColorgrayColor] CGColor]];
posted @ 2012-01-31 15:52 SuperHappy 閱讀(48) 評論(0) 編輯 NSNotificationCenter
建立一個繼承于UIViewControll的類,并在.m中添加如下代碼
-(void)doSomeThing:(NSNotification *)aNote
{
NSDictionary *dict = [aNote object];
NSLog(@"%@",dict);
}
- (void)loadView
{
[super loadView];
NSString *myString = @"some Value";
NSDictionary *myDict = [[NSDictionary alloc]initWithObjectsAndKeys:myString,@"first", nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomeThing:) name:@"notification" object:nil];
[[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:myDict];
}
設定通知:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomeThing:) name:@"notification" object:nil];
addObserver 這個是觀察者,就是說 在什麼地方接收通知;
selector 這個是收到通知後,調用何種方法;
name: 這個是通知的名字,也是通知的唯一标示,編譯器就通過這個找到通知的。
object: 對象,當設定為nil時,預設為所有名稱為以上消息名稱的(notification)都接收不管發送者是誰。
發送通知:
[[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:myDict];
postNotificationName:通知的名字,也是通知的唯一标示,編譯器就通過這個找到通知的。
object:對象,當設定為nil時,預設為所有名稱為以上消息名稱的(notification)都發送。
小例子僅僅是在一個類下的通知,實際來說通知更多的應用于不同的類之間傳遞資訊。
posted @ 2012-01-31 15:38 SuperHappy 閱讀(57) 評論(0) 編輯 簡單的大頭針地圖示示練習(無xib)
用4.2建立的空模班,添加的UIViewController類,取名為mapView.(按正規命名方式應該為MapView,大家見諒)。
以下為添加的代碼
mapView.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <QuartzCore/QuartzCore.h>
@interface mapView : UIViewController <CLLocationManagerDelegate>
{
CLLocationManager *locManager;
MKMapView *map;
CLLocation *bestLocation;
}
@property (retain) CLLocationManager *locManager;
@property (retain) CLLocation *bestLocation;
@end
mapView.m
//
// mapView.m
// Map
//
// Created by SuperHappy on 12-1-31.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "mapView.h"
#define BARBUTTON(TITLE, SELECTOR) [[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR] autorelease]
@implementation mapView
@synthesize locManager;
@synthesize bestLocation;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"Location manager error :%@",[error description]);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (!self.bestLocation) {
self.bestLocation = newLocation;
}
else if(newLocation.horizontalAccuracy < bestLocation.horizontalAccuracy)
self.bestLocation = newLocation;
map.region = MKCoordinateRegionMake(self.bestLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f));
map.showsUserLocation = YES;
map.zoomEnabled = NO;
}
- (void)findme
{
// disable right button
self.navigationItem.rightBarButtonItem = nil;
// Search for the best location
self.bestLocation = nil;
self.locManager.delegate = self;
[self.locManager startUpdatingLocation];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
[super loadView];
map = [[MKMapView alloc]initWithFrame:CGRectMake(10, 10, 300, 300)];
[self.view addSubview:map];
[map release];
self.navigationController.navigationBar.tintColor = [UIColor redColor];
self.locManager = [[[CLLocationManager alloc] init] autorelease];
if (!self.locManager.locationServicesEnabled)
{
NSLog(@"User has opted out of location services");
return;
}
else
{
// User generally allows location calls
self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
self.navigationItem.rightBarButtonItem = BARBUTTON(@"Find Me", @selector(findme));
}
}
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
posted @ 2012-01-31 14:13 SuperHappy 閱讀(26) 評論(0) 編輯 Object-c 總結之NSDate
NSDate的常見用法總結
// 目前時間建立NSDate
NSDate *myDate = [NSDate date];
NSLog(@"myDate = %@",myDate);
//從現在開始的24小時
NSTimeInterval secondsPerDay = 24*60*60;
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
NSLog(@"myDate = %@",tomorrow);
//根據已有日期建立日期
NSTimeInterval secondsPerDay1 = 24*60*60;
NSDate *now = [NSDate date];
NSDate *yesterDay = [now addTimeInterval:-secondsPerDay1];
NSLog(@"yesterDay = %@",yesterDay);
//比較日期
BOOL sameDate = [now isEqualToDate:yesterDay];
NSLog(@"sameDate = %lu",sameDate);
//擷取較早的日期
NSDate *earlierDate = [yesterDay earlierDate:now];
NSLog(@"earlierDate = %@",earlierDate);
//較晚的日期
NSDate *laterDate = [yesterDay laterDate:now];
NSLog(@"laterDate = %@",laterDate);
//兩個日期之間相隔多少秒
NSTimeInterval secondsBetweenDates= [yesterDay timeIntervalSinceDate:now];
NSLog(@"secondsBetweenDates= %lf",secondsBetweenDates);
//通過NSCALENDAR類來建立日期
NSDateComponents *comp = [[NSDateComponentsalloc]init];
[comp setMonth:06];
[comp setDay:01];
[comp setYear:2001];
NSCalendar *myCal = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *myDate1 = [myCal dateFromComponents:comp];
NSLog(@"myDate1 = %@",myDate1);
//從已有日期擷取日期
unsigned units = NSMonthCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit;
NSDateComponents *comp1 = [myCal components:units fromDate:now];
NSInteger month = [comp1 month];
NSInteger year = [comp1 year];
NSInteger day = [comp1 day];
//NSDateFormatter實作日期的輸出
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
[formatter setDateStyle:NSDateFormatterFullStyle];//直接輸出的話是機器碼
//或者是手動設定樣式[formatter setDateFormat:@"yyyy-mm-dd"];
NSString *string = [formatter stringFromDate:now];
NSLog(@"string = %@",string);
NSLog(@"formater = %@",formatter);
posted @ 2012-01-31 13:57 SuperHappy 閱讀(117) 評論(0) 編輯 Object-c 總結之NSDictionary
NSDictionary的常見用法總結
NSArray *array1 = [NSArray arrayWithObjects:@"iphone",@"ipod",nil];
NSArray *array2 = [NSArray arrayWithObjects:@"mac",@"imac",@"mac pro",nil];
//類方法初始化自動釋放
NSDictionary *myDictionary = [NSDictionary dictionaryWithObjectsAndKeys:array1,@"mobile",array2,@"computers",nil];//注意用nil結束
NSLog(@"myDictionary = %@",myDictionary);
int dictSize = [myDictionary count];
//通路字典中的值
NSArray *mobile = [myDictionary objectForKey:@"mobile"];
//從一個對象擷取鍵
NSArray *keys = [myDictionary allKeysForObject:array1];
//擷取字典中所有值得一個數組
NSArray *values = [myDictionary allValues];
//快速枚舉
for(id key in myDictionary)
{
NSLog(@"key: %@,value: %@",key,[myDictionary objectForKey:key]);
}
//如果字典隻包含屬性清單對象(NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary)可以儲存到檔案中
NSString *filePath = [[[NSBundlemainBundle]resourcePath]stringByAppendingPathComponent:@"dict.txt"];
BOOL success = [myDictionary writeToFile:filePath atomically:YES];
//用檔案填充
NSDictionary *myDict2 =[NSDictionary dictionaryWithContentsOfFile:filePath];
//可變字典
NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc]initWithObjectsAndKeys:array1,@"mobile",array2,@"computer", nil];
NSString *string4 = @"stringTV";
//修改對象
[dictMutable setObject:string4 forKey:@"media"];
//删除對象
[dictMutable removeObjectForKey:@"mobile"];
//删除多個對象
NSArray *keyArray =[NSArray arrayWithObjects:@"mobile",@"computer", nil];
[dictMutable removeObjectForKey:keyArray];
//删除所有對象
[dictMutable removeAllObjects];
posted @ 2012-01-31 13:54 SuperHappy 閱讀(217) 評論(0) 編輯 Object-c 總結之NSArray
NSArray的基本應用總結
NSString *string1 = @"two";
NSString *string2 = @"one";
//建立數組
NSArray *array1 = [NSArray arrayWithObjects:string1,string2, nil];
NSArray *array2 = [NSArray arrayWithArray:array1];
//建立數組隻包含已有數組的一部分
NSRange range = NSMakeRange(0, 2);
NSArray *subArray = [array1 subarrayWithRange:range];
//array的長度
int arrayLength = [array1 count];
//通路數組中特定位置的一個對象
NSString *string = [array1 objectAtIndex:0];
//是否包含指定對象
BOOL isInArray = [array1 containsObject:string1];
//對象在數組中的位置
int index = [array1 indexOfObject:string1];
//周遊一個數組中的值
for(NSString *obj in array1)
{
NSLog(@"%@",obj);
}
//反向周遊一個數組的值
for(NSString *objfan in [array1 reverseObjectEnumerator])
{
NSLog(@"%@",objfan);
}
//對字元串的重新排序(有點問題)
//[array1 sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
//NSLog(@"array1 = %@",array1);
//建立動态數組
NSMutableArray *myarray = [[NSMutableArray alloc]initWithObjects:string1,string2, nil];
NSString *string3 = @"Three";
//向動态數組中添加
[myarray addObject:string3];
[myarray addObject:string2];
[myarray insertObject:string3 atIndex:0];
[myarray insertObject:string2 atIndex:1];
//替換
[myarray replaceObjectAtIndex:1withObject:string3];
//删除
[myarray removeObject:string3];
//删除特定位置對象
[myarray removeObjectAtIndex:0];
//删除幾個對象
[myarray removeObjectsInRange:range];
//删除所有對象
[myarray removeAllObjects];
posted @ 2012-01-31 13:52 SuperHappy 閱讀(206) 評論(0) 編輯 Object-c 總結之NSString
參照《iphone SDK 3開發快速上手》編寫,特此聲明
//建立一個NSString
NSString *myString1 = @"some string";
NSLog(@"%@",myString1);
//格式化建立
NSString *myString2 = [NSString stringWithFormat:@"%@",myString1];
NSLog(@"%@",myString2);
//傳回數字的值
NSString *myString3 = @"1234abc";
double doubleString = [myString3 floatValue];//獲得123
NSLog(@"%f",doubleString);
int intString = [myString3 intValue];//獲得123
NSLog(@"%d",intString);
NSUInteger stringLenth = [myString3 length];
NSLog(@"%lu",stringLenth);
//比較兩個字元串,若相同傳回TURE
BOOL areEqual =
[myString1 isEqualToString:myString2];
NSLog(@"areEqual = %d",areEqual);
//區分大小寫的比較
BOOL areEqual1 = ([myString1 caseInsensitiveCompare:myString2] == NSOrderedSame);
NSLog(@"areEqual1 = %d",areEqual1);
//轉換大小寫
NSString *myString4 = @"asdfg";
NSString *upper = [myString4 uppercaseString];
NSString *lower = [upper lowercaseString];
NSLog(@"upper = %@",upper);
NSLog(@"lower = %@",lower);
//截去字元串(以空格為例)
NSString *myString5 = @" one two three ";
NSString *trimmed1 = [myString5 stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]];
//whitespaceAndNewlineCharacterSet去除前後的空格和換行符
NSString *trimmed2 = [myString5 stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];
//whitespaceCharacterSet 去除前後的空格,實際效果來看隻實作了去除首字母前面的空格
NSLog(@"myString5 = %@",myString5);
NSLog(@"trimmed1 = %@",trimmed1);
NSLog(@"trimmed2 = %@",trimmed2);
//predicate 斷言斷定,使基于,下面的方法實作删除空格
NSPredicate *noE = [NSPredicatepredicateWithFormat:@"SELF!=''"];
NSArray *part = [myString5 componentsSeparatedByCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];
NSArray *file = [part filteredArrayUsingPredicate:noE];
NSString *trimmed3 = [file componentsJoinedByString:@""];
NSLog(@"trimmed3 = %@",trimmed3);
//有已知字元串建立子字元串
NSString * number = @"abx cdefghi gklmn";
//substringToIndex擷取字元串的前三個
//substringFromIndex從第三個開始截取到最後
NSString *myString6 = [number substringToIndex:3];
NSLog(@"myString6 = %@",myString6);
NSRange range = NSMakeRange(4, 5);
//用邊界截取起始位置為第四個,長度為5個長度
NSString *aString = [number substringWithRange:range];
NSLog(@"aString = %@",aString);
//建立成數組
NSArray *arr = [number componentsSeparatedByString:@" "];
NSLog(@"arr = %@",arr);
//替換子字元串
NSString *myString7 = [number stringByReplacingOccurrencesOfString:@"efg"withString:@"aaa"];
NSLog(@"myString7 = %@",myString7);
//查找子字元串,這段代碼傳回(4,3);
NSRange found = [number rangeOfString:@"cde"];
NSLog(@"found.location = %lu",found.location);
NSLog(@"%lu",found.length);
//判讀那是否包含
BOOL found1 = ([number rangeOfString:@"cde"].location !=NSNotFound);
NSLog(@"found1 = %lu",found1);
//組合字元串
NSString *myString9 = [myString1 stringByAppendingString:myString7];
NSLog(@"myString9 = %@,myString1 = %@,myString7 = %@",myString9,myString1,myString7);
NSString *myString10 = [myString1 stringByAppendingFormat:myString7];
NSLog(@"myString10 = %@,myString1 = %@,myString7 = %@",myString10,myString1,myString7);
//将檔案内容寫入到字元串中
NSString *fileContents = [NSString stringWithContentsOfFile:@"123.text"];
//擷取檔案擴充名
NSString *filename = @"11111.txt";
NSString *fileExtension = [filename pathExtension];
NSLog(@"fileExtension = %@",fileExtension);
//将URL内容寫入字元串,有點問題
NSURL *url = [NSURLURLWithString:@"http://www.baidu.com"];
NSLog(@"url = %@",url);
NSString *pageContents = [NSString stringWithContentsOfURL:url];
//NSLog(@"pageContents = %@",pageContents);
posted @ 2012-01-31 13:50 SuperHappy 閱讀(223) 評論(0) 編輯 iphone記憶體管理的一些整理
記憶體管理個人總結
無論編寫任何程式,都需要確定能夠有效和高效地管理資源。程式記憶體就是這些資源中的一種。在Objective-C程式中,必須確定所建立的對象,在不再需要它們的時候被銷毀。
注意:iOS不提供垃圾回收機制。
一般規則:
隻能釋放或自動釋放自己所擁有的對象
一般以alloc ,new, copy建立的對象都具有所有權,或者如果向一個對象發送了一條retain消息,也會獲得該對象的所有權。
此時需要用release進行釋放或者調用自動釋放池autorelease;自動釋放池的調用是系統來完成的。
需要将接收到的對象存儲為某個執行個體變量的屬性,您必須保留或複制該對象。
釋放執行個體:
UIView *view 1= [[UIView alloc]init];
Self.view = view1;
[view1 release];
不需要釋放的例子:
UIButton*button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
由于調用的類方法沒有使用alloc,new,copy等是以它自動釋放,不需要手動釋放。
調用自動釋放池的例子:
-(NSArray *)rearray
{
NSArray *array = [[NSArray alloc]initWithObjects:@”1”,@”2”,nil];
return [array autorelease];
}
這個方法既沒有破壞記憶體規則,又避免了接收值的使用者不知道何時銷毀對象的現象。如果直接return array會造成記憶體洩露,如果先釋放在傳回的話會傳回無效對象([array release];return array;)這也是錯誤的。當然如果直接調用類方法就可以這樣做:
-(NSArray *)rearray
{
NSArray *array = [NSArray arrayWithObjects:@”1”,@”2”,nil];
return array;
}
在 Objective-C 程式中,對象會被建立和銷毀。為了確定應用程式不會使用不必要的記憶體,對象應該在不需要它們的時候被銷毀。當然,在需要對象時保證它們不被銷毀也很重要。
任何對象都可能擁有一個或多個所有者。隻要一個對象至少還擁有一個所有者,它就會繼續存在。如果一個對象沒有所有者,則運作時系統會自動銷毀它。
可以使用retain來獲得一個對象的所有權。
保留計數(retainCount)
在調用retain方法後通過引用計數—通常被稱為“保留計數”—實作的。每個對象都有一個保留計數。
建立一個對象時,該對象的保留計數為1。
向一個對象發送retain消息時,該對象的保留計數加1。
向一個對象發送release消息時,該對象的保留計數減1。
向一個對象發送autorelease消息時,該對象的保留計數會在将來的某個階段減1。
如果一個對象的保留計數被減為0,該對象就會被回收.(直接調用dealloc進行釋放)。
當顯式地查詢對象的保留計數是多少。由于添加了保護機制,當保留計數被減為0時,控制台輸出仍然為1是以會造成誤導。
共享對象的有效性
Cocoa的所有權政策規定,被接收的對象通常應該在整個調用方法的作用域内保持有效。此外,還可以傳回從目前作用域接收到的對象,而不必擔心它被釋放。對象的getter方法傳回一個緩存的執行個體變量或者一個計算值,這對您的應用程式來說無關緊要。重要的是,對象會在您需要它的這段期間保持有效。
這一規則偶爾也有一些例外情況,主要可以總結為以下兩類。
當對象從一個基本的集合類中被删除的時候。
heisenObject = [array objectAtIndex:n];
[array removeObjectAtIndex:n];
// heisenObject could now be invalid.
當對象從一個基本的集合類中被删除時,它會收到一條release(不是autorelease)消息。如果該集合是這個被删除對象的唯一所有者,則被删除的對象(例子中的heisenObject)将被立即回收。
當一個“父對象”被回收的時候。
id parent = <#create a parent object#>;
// ...
heisenObject = [parent child] ;
[parent release]; // Or, for example: self.parent = nil;
// heisenObject could now be invalid.
在某些情況下,您通過另外一個對象得到某個對象,然後直接或間接地釋放父對象。如果釋放父對象會使其被回收,而且父對象是子對象的唯一所有者,那麼子對象(例子中的heisenObject)将同時被回收(假設它在父對象的dealloc方法中收到一條release而非autorelease消息)。
為了防止這些情況發生,您要在接收heisenObject後保留該對象,并
在使用完該對象後對其進行釋放,例如:
heisenObject = [[array objectAtIndex:n] retain];
[array removeObjectAtIndex:n];
// use heisenObject.
[heisenObject release];
如果在您的類中有執行個體變量對象,您必須實作一個dealloc方法來釋放它們,然後調用超類的dealloc實作。
重要:決不要直接調用另一個對象的dealloc方法。
保留循環
在某些情況下,兩個對象之間可能會出現循環引用的情況,也就是說,每一個對象都包含一個執行個體變量引用對方對象。例如,考慮一個文本程式,程式中對象間的關系如圖1所示。“文檔(Document)”對象為文檔中的每個頁面建立一個“頁(Page)”對象。每個Page對象具有一個執行個體變量,用來跟蹤該頁所在的文檔。如果Document對象保留了Page對象, 同時Page對象也保留Document對象,則這兩個對象都永遠不會被釋放。隻有Page對象被釋放,Document的引用計數才能變為0,而隻有Document對象被回收,Page對象才能被釋放。
針對保留循環問題的解決方案是“父”對象應保留其“子”對象,但子對象不應該保留其父對象。是以,在圖1中,document對象要保留page對象,但page對象不保留document對象。子對象對其父對象的引用是一個弱引用的例子,這部分内容在“對象的弱引用”有更充分的描述。
保留一個對象建立了一個對該對象的“強”引用。一個對象隻有在它的所有強引用都被釋放後才能被回收。是以,一個對象的生命周期取決于其強引用的所有者。在某些情況下,這種行為可能并不理想。您可能想要引用一個對象而不妨礙對象本身的回收。對于這種情況,您可以擷取一個“弱”引用。弱引用是通過存儲一個指向對象的指針建立的,而不是保留對象。
NSMutableArray *array;
NSUInteger i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *allocedNumber = [[NSNumber alloc] initWithInteger: i];
[array addObject:allocedNumber];
[allocedNumber release];
}
在這段代碼中,您需要在for循環的作用域内向allocedNumber發送release消息,以抵消之前的alloc。由于數組在用addObject:方法添加數字時對其進行了保留,是以隻要它還在數組中就不會被釋放。
要了解這一點,您要把自己放在實作這種集合類的作者的位置。您要確定交給您管理的對象不能在您的眼皮底下消失,是以您要在這些對象被加入集合中時向它們發送retain消息。如果它們被删除,您還必須相應地發送release消息,并且在您自己的dealloc方法中,您還應該向其餘的對象發送release消息。
您可以使用常見的alloc和init消息來建立一個NSAutoreleasePool對象,并使用drain(如果您向一個自動釋放池發送autorelease或retain消息,會引發異常—要了解release和drain之間的差異,請參考“垃圾回收”)銷毀它。自動釋放池應該總是在與它被建立時所處的相同上下文環境(方法或函數的調用,或循環體)中被銷毀。
自動釋放池被置于一個堆棧中,雖然它們通常被稱為被“嵌套”的。當您建立一個新的自動釋放池時,它被添加到堆棧的頂部。當自動釋放池被回收時,它們從堆棧中被删除。當一個對象收到送autorelease消息時,它被添加到目前線程的目前處于棧頂的自動釋放池中。
嵌套自動釋放池的能力是指,您可以将它們包含進任何函數或方法中。例如,main函數可以建立一個自動釋放池,并調用另一個建立了另外一個自動釋放池的函數。或者,一個方法可以有一個自動釋放池用于外循環,而有另一個自動釋放池用于内循環。嵌套自動釋放池的能力是一種很顯著的優勢,但是,當發生異常時也會有副作用
我們通常會提及自動釋放池是被嵌套的,如清單1所示。但是,您也可以認為嵌套自動釋放池位于一個堆棧中,其中,“最内層”的自動釋放池位于棧頂。如前所述,嵌套自動釋放池實際上是這樣實作的:程式中的每個線程都維護一個自動釋放池的堆棧。當您建立一個自動釋放池時,它被壓入目前線程的堆棧的棧頂。當一個對象被自動釋放時—也就是說,當一個對象收到一條autorelease消息或者當它作為一個參數被傳入addObject:類方法時—它總是被放入堆棧頂部的自動釋放池中。
在垃圾回收環境中,release是一個空操作。是以,NSAutoreleasePool提供了drain方法,在引用計數環境中,該方法的作用等同于調用release,但在垃圾回收環境中,它會觸發垃圾回收(如果自上次垃圾回收以來配置設定的記憶體大于目前的門檻值)。是以,在通常情況下,您應該使用drain而不是release來銷毀自動釋放池。