iOS 小知識

1代碼中字符串換行

?NSString *string = @"ABCDEFGHIJKL" \

?"MNOPQRSTUVsWXYZ";

?2沒有用到類的成員變量的,都寫成類方法

?3category可以用來調試可以隱藏私有方法,最主要的是用它截住函數。

?例1:測試時我想知道TableViewCell有沒有釋放,就可以這樣寫

?@implementationUITableViewCell(dealloc)

-(void)dealloc ?{

NSLog(@"%@",NSStringFromSelector(_cmd));

?NSArray *array = allSubviews(self);

?// allSubviews是cookBook里的函數,可以取一個view的所有subView ,在這個文檔后面也有

NSLog(@"%@",array);

[super dealloc];

}

@end

例2:我調試程序,覺得table的大小變了,想找到在哪改變的,這樣做:@implementation UITableView(set frame)

-(void)setFrame:(CGRect)frame {

NSLog(%"%@",self);[super setFrame: frame];

}

@end

?category和exension的區別:

?category:

?a.類別是一種為現有的類添加新方法的方式。利用Objective-C的動態運行時分配機制,Category提供了一種比繼承(inheritance)更為簡潔的方法來對class進行擴展,無需創建對象類的子類就能為現有的類添加新方法,可以為任何已經存在的class添加方法,包括那些沒有源代碼的類(如某些框架類)。

?b.聲明類別

?@interface NSArray (MArrayCateoryDemo)

?-(NSArray*) orderByTime;

?@end

?實現類別

?@implementation NSArray (MArrayCateoryDemo)

?-(NSArray*) orderByTime {

?NSArray *demo = [self ...];

?return demo;

?}

?@end

?調用:NSArray * array = ..;NSArray = [array orderByTime];

?三、類別的局限性有兩方面局限性:

?(1)無法向類中添加新的實例變量,類別沒有位置容納實例變量。

?(2)名稱沖突,即當類別中的方法與原始類方法名稱沖突時,類別具有更高的優先級。類別方法將完全取代初始方法從而無法再使用初始方法。

?c 類別的作用類別主要有3個作用:

?(1)可以將類的實現分散到多個不同文件或多個不同框架中,方便代碼管理。也可以對框架提供類的擴展(沒有源碼,不能修改)。

?(2)創建對私有方法的前向引用:如果其他類中的方法未實現,在你訪問其他類的私有方法時編譯器報錯這時使用類別,在類別中聲明這些方法(不必提供方法實現),編譯器就不會再產生警告

?(3)向對象添加非正式協議:創建一個NSObject的類別稱為“創建一個非正式協議”,因為可以作為任何類的委托對象使用。

?5. extension

?@interface MyObject()

{

?int extension;

?}

?-(void)testInExtension;

?@end

?他們的主要區別是:

?1、形式上來看,extension是匿名的category。

?2、extension里聲明的方法需要在mainimplementation中實現,category不強制要求。

?3、extension可以添加屬性(變量),category不可以。

?6. block聲明 blockvoid(^blockDemo)(void);

?定義blockblockDemo = ^{...};

?聲明和定義在一起void(^blockDemo)(void) = ^ {...};

?前面一個void是返回值類型,后面括號里面void是參數類型,此例中表明沒有返回值和參數。

?如何使用舉例:比如請求網絡數據,聲明一個block用來傳遞請求到的數據:void(^requestData)(NSData *id);定義一個獲取數據的方法

?- (void)requestDataWithBlock:(void (^)(NSData* data))pBlock {

?NSData *data = [NSData data];

?pBlock(data);

?}

?調用該方法去獲取數據。

?[self requestDataWithBlock:^(NSData *data) {

?if (data) {...} else {...}

?}];

?為了延長block的生命周期,可以將其聲明為類的成員變量。

?typedef void(^blockDemo)(void);

?@interface MyObject() {blockDemo demoBlock;}@end

?很需要注意的一點就是,block內local variable是會自動做retain的, 而用到的外部成員也會自動retain, 而這就很容易造成retain cycle。為了解決這個問題,在使用外部成員時都應該在使用之前加上__block。

?7.使用自定義字體

?1.添加對應的字體(.ttf或.odf)到工程的resurce,例如my.ttf。

?2.在info.plist中添加一項 Fonts provided by application (item0對應的value為my.ttf,添加多個字體依次添加就可以了)。

?3.使用時aLabel.font=[UIFontfontWithName:@"XXX" size:30]; 注意XXX不一定是my,這里是RETURN TO CASTLE??梢杂萌缦路椒ú榭磃amilyname和font name:

?NSArray *familyNames = [UIFontfamilyNames];

?for( NSString *familyNameinfamilyNames ){

?printf( "Family: %s \n", [familyNameUTF8String] );

?NSArray *fontNames = [UIFontfontNamesForFamilyName:familyName];

?for( NSString *fontNameinfontNames ){

?printf( "\tFont: %s \n", [fontNameUTF8String] );

?}}

?8后臺運行IOS允許長時間在后臺運行的情況有7種:

?audio

?VoIP

?GPS

?下載新聞

?和其它附屬硬件進行通訊時

?使用藍牙進行通訊時

?使用藍牙共享數據時

?除以上情況,程序退出時可能設置短暫運行10分鐘

?9 關于UITableView

?任意設置Cell選中狀態的背景色:

?UIView *bgView = [[UIView alloc] init];

?bgView.backgroundColor = [UIColor orangeColor];

?self.selectedBackgroundView = bgView;[bgView release];

?該方法設置的是純色, 也可以使用任何圖片,把selectedBackgroundView設成UIImageView。但要注意,選中取消時,需要取消顏色,self.selectedBackgroundView = nil,否則顏色一直在。除了上面的方法,前幾天發現了一個新方法:重寫UITableViewCell 的setSelected:animated:方法

-(void)setSelected:(BOOL)selected animated:(BOOL)animated{

?[super setSelected:selected animated:animated];

?if (selected) {

?self.backgroundColor = RGB(224, 152, 40);

?}else {

self.backgroundColor = [UIColor clearColor];

?}

}

?flashScrollIndicators這個很有用,閃一下滾動條,暗示是否有可滾動的內容??梢栽赩iewDidAppear或[table reload]之后調用。

?點擊Cell中的按鈕時,如何取所在的Cell:

?-(void)OnTouchBtnInCell:(UIButton *)btn {

?CGPoint point = btn.center;

point = [table convertPoint:point fromView:btn.superview];

NSIndexPath* indexpath = [table indexPathForRowAtPoint:point];UITableViewCell *cell = [table cellForRowAtIndexPath:indexpath];

...// 也可以通過一路取btn的父窗口取到cell,但如果cell下通過好幾層subview才到btn,就要取好幾次 superview// 所以我用上面的方法,比較通用。這種方法也適用于其它控件。 }

?10. 理解@selector()

?可以理解 @selector()就是取類的成員方法的編號,他的行為基本可以等同C語言的中函數指針,只不過C語言中,可以把函數名直接賦給一個函數指針,而Object-C的類不能直接應用函數指針,這樣只能做一個@selector語法來取.

?它的結果是一個SEL類型。這個類型本質是類方法的編號(函數地址)可以聲明一個SEL類型的變量。如:SEL _MyMethod;SEL一般用作參數傳遞, 以下這個簡單的例子便是系統中使用@selector的場景和原理,比如給自定義控件或者XIB中的控件關聯事件相應方法,基本上就是這樣做的,熟悉掌握@selector的原理和流程,可以為我們的編程帶來極大的便利。

?@interface A : NSObject {

?SEL _AMehtod;

?Other_Class_Instance id;

?}

?- (void)popUpAWarningDialogWithTarget:(id)pTarget seelctor:(SEL)pSel;

?@end

?@implementA

?- (void)popUpAWarningDialogWithTarget:(id)pTarget seelctor:(SEL)pSel {

?id = pTarget;

?_AMethod = pSel;

[self handleSelecter];

?}

- (void)handleSelect {

?if ([id respondsToSelector:_AMethod]) {

?[id performSelector:_AMethod];

?}

?}

?@end

?@interface B:NSObject{

?A *_a;

?}

?@end

?@implement B

?- (void)testSelector {

?_a = [A alloc] init];

?[_a popUpAWarningDialogWithTarget:selfseelctor:@selector(pupUpDialog)];

?}

?- (void)pupUpDialog {

?NSLog(@"It's called!");

?}

?@end

?11.一個不停震動的方法:// 定義一個回調函數,震動結束時再次發出震動

?void MyAudioServicesSystemSoundCompletionProc (SystemSoundIDssID,void *clientData){

?BOOL* iShouldKeepBuzzing = clientData;

?if (*iShouldKeepBuzzing) {AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

?} else {

?//Unregister, so we don't get called again...AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);

?}

}以下為調用的代碼:

?BOOL iShouldKeepBuzzing = YES;

?AudioServicesAddSystemSoundCompletion (kSystemSoundID_Vibrate,NULL,NULL,MyAudioServicesSystemSoundCompletionProc,&iShouldKeepBuzzing );

?AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);

?12去掉app圖標的發光效果info.plist里增加Icon already includes gloss effects,值設為YES ]

?13UIColor colorWithRed:green:blue:alpha:這個方法的參數必須用浮點型。假如使用Xcode自帶的取顏色的工具,取到的RGB值分別為:25,25,25,傳給上述方法的參數應為25/255.0或25.0/255。如果用整型25/255,經過取整,小數部分沒有了,顯示出來的顏色和取到的是不一樣的??梢远x一個宏:

?#define RGB(A,B,C) [UIColor colorWithRed:A/255.0 green:B/255.0 blue:C/255.0 alpha:1.0]

?然后用RGB(25,25,25)就可以了

?14禁止textField和textView的復制粘貼菜單:

?-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{

?if ([UIMenuController sharedMenuController]) {

?[UIMenuController sharedMenuController].menuVisible = NO;

?}

?return NO;

?}

?15loadView如果重載loadView,一定要在這個方法里產生一個self.view。可以調用[super loadView],也可以使用alloc+init。因為在該函數時,self.view為nil,如果直接調用self.member的話,也就是loadView不斷調用loadView,進入了死循環 。

?16如何進入軟件在app store 的頁面:先用iTunes Link Maker找到軟件在訪問地址,格式為itms-apps://ax.itunes.apple.com/...,

然后#defineITUNESLINK@"itms-apps://ax.itunes.apple.com/..."

?NSURL *url = [NSURL URLWithString:ITUNESLINK];

?if([[UIApplication sharedApplication] canOpenURL:url]){

?[[UIApplication sharedApplication] openURL:url];}

?如果把上述地址中itms-apps改為http就可以在瀏覽器中打開了??梢园堰@個地址放在自己的網站里,鏈接到app store。iTunes Link Maker地址:http://itunes.apple.com/linkmaker

?17禁止程序運行時自動鎖屏[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

?18改變UIAlertView背景UIAlertView默認是半透明的,會透出背景的內容,有時看著有些混亂??梢詫憘€改變背景的方法changeBackground。

@interfaceUIAlertView (changeBK)

- (void)changeBackground;

@end

?@implementationUIAlertView (changeBK)

- (void)changeBackground{

for(UIView* vin[selfsubviews]){

?if([visKindOfClass:[UIImageView class]]) {

?UIImage*theImage = [UIImageimageNamed:@"AlertView.png"];((UIImageView*)v).image= theImage;

?break;

?}

}

}

@end

在[alertView show]之后或willPresentAlertView:中調用即可。// UIAlertView *alertView = [UIAlertView alloc] init ......[alertView show];[alertView changeBackgro

?19 改變UITextField的背景可以給textField加好看的邊框等

?@interface UITextField (changeBK)

-(void)orangeBackground;

@end@implementation UITextField (changeBK)

-(void)orangeBackground{

self.background = [[UIImage imageNamed:@"fieldBK.png"]stretchableImageWithLeftCapWidth:5 topCapHeight:5];}

@end

?20取常用的地址Document:NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

?NSString *documentsDirectory = [paths objectAtIndex:0];

?Library:

?NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

?NSString *libraryDirectory = [paths objectAtIndex:0];

??21如何改變UINavigationBar的背景針對較舊的IOS,大概是IOS 4.3及以下:@implementation UINavigationBar (CustomImage)- (void)drawRect:(CGRect)rect{UIImage *image = [[UIImage imageNamed: @"navBar"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];[image drawInRect:CGRectMake(0, 0.5, self.frame.size.width, self.frame.size.height)];}@end

?針對所有版本IOS:@implementation UINavigationBar (selBackground)

?-(void)setToCustomImage{

?if ([[UIDevice currentDevice] systemVersion].floatValue >= 5.0 ) {

?[self setBackgroundImage:[UIImage imageNamed:@"navBar"] forBarMetrics:UIBarMetricsDefault];

}else{

?self.layer.contents = (id)[UIImage imageNamed:@"navBar"].CGImage;}}

?@end

?22自IOS 6.0,為了控制旋轉,要給UINavigationController寫個category(原因見以下黃色背景的內容)

?@interface UINavigationController (Rotate)

?@end

?@implementation UINavigationController (Rotate)

?- (NSUInteger)supportedInterfaceOrientations{

?return [self.topViewController supportedInterfaceOrientations];

?}

?- (BOOL)shouldAutorotate{

?return [self.topViewController shouldAutorotate];}

?@end

?23簡化代碼用的define

?#define SETRGBSTROKECOLOR(ctx,R,G,B) CGContextSetRGBStrokeColor(context, R/255.0, G/255.0, B/255.0, 1.0)

?#define SETRGBFILLCOLOR(ctx,R,G,B) CGContextSetRGBFillColor(context, R/255.0, G/255.0, B/255.0, 1.0)

?#define _ADDOBSERVER(TITLE, SELECTOR) [[NSNotificationCenter defaultCenter] addObserver:self selector:SELECTOR name:TITLE object:nil]

?#define _REMOVEOBSERVER(id) [[NSNotificationCenter defaultCenter] removeObserver:id]

?#define _POSTNOTIFY(TITLE,OBJ,PARAM) [[NSNotificationCenter defaultCenter] postNotificationName:TITLE object:OBJ userInfo:PARAM]

?24 如何加大按鈕的點擊范圍:

?1.把UIButton的frame 設置的大一些,然后給UIButton設置一個小些的圖片[tmpBtn setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];// 注意這里不能用setBackgroundImage[tmpBtn setImage:[UIImage imageNamed:@"testBtnImage"] forState:UIControlStateNormal];

?2.使用類UIButton (hitTest)。這是一個開源類

?25 有時iPhone或iPad檢測設備旋轉不準確加上這個通知就可以了:_ADDOBSERVER(UIDeviceOrientationDidChangeNotification, @selector(didRotateNotification));

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容