1拓挥、c語言回調(diào)可以用self的靜態(tài)傳入調(diào)用方法暂衡,也可以用類設(shè)置delegate傳出來朵耕,記得置nil
static class objectSelf;
objectSelf = self;
void cFunction(){
[objectSelf invokeOCFunction];
}
ps:記得在合適的地方把objectSelf置nil
2似袁、try catch 時要注意內(nèi)存管理
try catch 時要注意內(nèi)存管理攘轩,MRC下可以增加@finally中release對象;
但是在ARC中時叉存,系統(tǒng)是在allocinit之后插入的內(nèi)存管理代碼,在trycatch一樣會受到影響度帮,這樣會導(dǎo)致內(nèi)存泄露(占用的棧內(nèi)存歼捏,由系統(tǒng)管理,多了會影響app性能)笨篷;
解決辦法是可以打開文件的-fobjc-arc-exceptions瞳秽,讓系統(tǒng)增加異常安全處理代碼來跟蹤清理對象,在objective-c++中率翅,這個會默認(rèn)開啟练俐。(備注:開啟這個并不理想,這樣的處理多了還會影響性能冕臭,因此oc中最好用error保證代碼質(zhì)量腺晾,而不是try-catch,而且oc中trycatch能捕獲的異常我們基本都能預(yù)防燕锥,所以try catch很少用)
例如下面的代碼就有問題:
@try{
NSMutableArray * a = @[@"1",@"2"].mutableCopy;
[a removeObjectAtIndex:3];
}@catch(NSException * ex){
NSLog(@"reason:%@",ex.reason);
}
可以用自動釋放池來處理:
for (int i = 0 ; i< 10000; i++) {
@autoreleasepool{
@try{
NSMutableArray * a = [[NSMutableArray alloc] initWithArray:@[@"1",@"2"]];
[a removeObjectAtIndex:3];
}@catch(NSException * ex){
NSLog(@"reason:%@",ex.reason);
}
}
}
3、委托模式delegate
自己寫的委托模式下每次都要調(diào)用response方法,這個會影響性能悯蝉,可以在setdelegate的時候归形,設(shè)置unsigned int:1 的結(jié)構(gòu)體,能響應(yīng)鼻由,設(shè)值為1暇榴,這樣在response的時候判斷是不是1就可以了
typedef struct{
unsigned int canResponse :1;///可以表示0~1(位段,bitfield)
unsigned int canResponseEight : 8;///表示0~255
}DelegateResponse;
{
DelegateResponse delegateResponse;
}
- (void)setDelegate:(id<AAAProtocol>)delegate{
_delegate = delegate;
delegateResponse.canResponse = [_delegate respondsToSelector:@selector(eat)];
}
if (delegateResponse.canResponse) {
[self.delegate function];
}
4蕉世、盡可能少引入頭文件
優(yōu)化編譯速度跺撼,引入的頭文件盡可能的少,比如只是用到類名讨彼,可以用@class
參考資料:《編寫高質(zhì)量ios與os x代碼的52個有效方法》