iOS 小知識

1代碼中字符串換行

?NSString *string = @"ABCDEFGHIJKL" \

?"MNOPQRSTUVsWXYZ";

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

?3category可以用來調(diào)試可以隱藏私有方法,最主要的是用它截住函數(shù)。

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

?@implementationUITableViewCell(dealloc)

-(void)dealloc ?{

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

?NSArray *array = allSubviews(self);

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

NSLog(@"%@",array);

[super dealloc];

}

@end

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

-(void)setFrame:(CGRect)frame {

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

}

@end

?category和exension的區(qū)別:

?category:

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

?b.聲明類別

?@interface NSArray (MArrayCateoryDemo)

?-(NSArray*) orderByTime;

?@end

?實現(xiàn)類別

?@implementation NSArray (MArrayCateoryDemo)

?-(NSArray*) orderByTime {

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

?return demo;

?}

?@end

?調(diào)用:NSArray * array = ..;NSArray = [array orderByTime];

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

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

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

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

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

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

?(3)向?qū)ο筇砑臃钦絽f(xié)議:創(chuàng)建一個NSObject的類別稱為“創(chuàng)建一個非正式協(xié)議”,因為可以作為任何類的委托對象使用。

?5. extension

?@interface MyObject()

{

?int extension;

?}

?-(void)testInExtension;

?@end

?他們的主要區(qū)別是:

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

?2、extension里聲明的方法需要在mainimplementation中實現(xiàn),category不強(qiáng)制要求。

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

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

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

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

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

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

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

?NSData *data = [NSData data];

?pBlock(data);

?}

?調(diào)用該方法去獲取數(shù)據(jù)。

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

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

?}];

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

?typedef void(^blockDemo)(void);

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

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

?7.使用自定義字體

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

?2.在info.plist中添加一項 Fonts provided by application (item0對應(yīng)的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

?下載新聞

?和其它附屬硬件進(jìn)行通訊時

?使用藍(lán)牙進(jìn)行通訊時

?使用藍(lán)牙共享數(shù)據(jù)時

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

?9 關(guān)于UITableView

?任意設(shè)置Cell選中狀態(tài)的背景色:

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

?bgView.backgroundColor = [UIColor orangeColor];

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

?該方法設(shè)置的是純色, 也可以使用任何圖片,把selectedBackgroundView設(shè)成UIImageView。但要注意,選中取消時,需要取消顏色,self.selectedBackgroundView = nil,否則顏色一直在。除了上面的方法,前幾天發(fā)現(xiàn)了一個新方法:重寫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這個很有用,閃一下滾動條,暗示是否有可滾動的內(nèi)容??梢栽赩iewDidAppear或[table reload]之后調(diào)用。

?點擊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語言的中函數(shù)指針,只不過C語言中,可以把函數(shù)名直接賦給一個函數(shù)指針,而Object-C的類不能直接應(yīng)用函數(shù)指針,這樣只能做一個@selector語法來取.

?它的結(jié)果是一個SEL類型。這個類型本質(zhì)是類方法的編號(函數(shù)地址)可以聲明一個SEL類型的變量。如:SEL _MyMethod;SEL一般用作參數(shù)傳遞, 以下這個簡單的例子便是系統(tǒng)中使用@selector的場景和原理,比如給自定義控件或者XIB中的控件關(guān)聯(lián)事件相應(yīng)方法,基本上就是這樣做的,熟悉掌握@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.一個不停震動的方法:// 定義一個回調(diào)函數(shù),震動結(jié)束時再次發(fā)出震動

?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);

?}

}以下為調(diào)用的代碼:

?BOOL iShouldKeepBuzzing = YES;

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

?AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);

?12去掉app圖標(biāo)的發(fā)光效果info.plist里增加Icon already includes gloss effects,值設(shè)為YES ]

?13UIColor colorWithRed:green:blue:alpha:這個方法的參數(shù)必須用浮點型。假如使用Xcode自帶的取顏色的工具,取到的RGB值分別為:25,25,25,傳給上述方法的參數(shù)應(yīng)為25/255.0或25.0/255。如果用整型25/255,經(jīng)過取整,小數(shù)部分沒有了,顯示出來的顏色和取到的是不一樣的??梢远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的復(fù)制粘貼菜單:

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

?if ([UIMenuController sharedMenuController]) {

?[UIMenuController sharedMenuController].menuVisible = NO;

?}

?return NO;

?}

?15loadView如果重載loadView,一定要在這個方法里產(chǎn)生一個self.view??梢哉{(diào)用[super loadView],也可以使用alloc+init。因為在該函數(shù)時,self.view為nil,如果直接調(diào)用self.member的話,也就是loadView不斷調(diào)用loadView,進(jìn)入了死循環(huán) 。

?16如何進(jìn)入軟件在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就可以在瀏覽器中打開了??梢园堰@個地址放在自己的網(wǎng)站里,鏈接到app store。iTunes Link Maker地址:http://itunes.apple.com/linkmaker

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

?18改變UIAlertView背景UIAlertView默認(rèn)是半透明的,會透出背景的內(nèi)容,有時看著有些混亂??梢詫憘€改變背景的方法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:中調(diào)用即可。// 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,為了控制旋轉(zhuǎn),要給UINavigationController寫個category(原因見以下黃色背景的內(nèi)容)

?@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 設(shè)置的大一些,然后給UIButton設(shè)置一個小些的圖片[tmpBtn setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];// 注意這里不能用setBackgroundImage[tmpBtn setImage:[UIImage imageNamed:@"testBtnImage"] forState:UIControlStateNormal];

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容