iOS


資料


面試


Tips

  • Swift打印內(nèi)存地址
println(" str value \(str) has address: \(unsafeAddressOf(str))")
  • Obj-C屏蔽警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations" 
...
#pragma clang diagnostic pop
  • 打印代碼文件中函數(shù)的調(diào)用過程
    clang -rewrite-objc xxx.m
    
  • UIWebView獲取Html標(biāo)題
-(void)webViewDidFinishLoad:(UIWebView *)webView {    
    titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
  • Category添加屬性字段
@interface UIImage (category)
// 在UIImage中新建一個(gè)tag屬性
@property (nonatomic, copy) NSString *tag;
@end
static const void *tagKey = &tagKey;
@implementation UIImage (category)
-(NSString *)tag { 
    return objc_getAssociatedObject(self, tagKey);
}
-(void)setTag:(NSString *)tag { 
    objc_setAssociatedObject(self, tagKey, tag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
  • 隱藏狀態(tài)欄
override func prefersStatusBarHidden() -> Bool { return true }
  • Runloop實(shí)現(xiàn)Alert同步彈窗
-(NSInteger)doModal {
    [self showAlert];
    _bModel = YES;
    while (_bModel) {
      [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
    return _selectBtnIndex;
}
-(void)showAlert {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"okookoko" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
    [alertView show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    _selectBtnIndex = buttonIndex;
    _bModel = NO;
}
  • UITableView的Group樣式下頂部空白處理
//分組列表頭部空白處理
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;
  • 禁止鎖屏

默認(rèn)情況下痕惋,當(dāng)設(shè)備一段時(shí)間沒有觸控動(dòng)作時(shí)分瘦,iOS會(huì)鎖住屏幕。但有一些應(yīng)用是不需要鎖屏的,比如視頻播放器逼裆。

[UIApplication sharedApplication].idleTimerDisabled = YES;
  • 模態(tài)推出透明界面
UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
} else {
    self.modalPresentationStyle=UIModalPresentationCurrentContext;
}
[self presentViewController:na animated:YES completion:nil];
  • Xcode調(diào)試不顯示內(nèi)存占用

editSCheme 里面有個(gè)選項(xiàng)叫叫做enable zoombie Objects 取消選中

  • 顯示隱藏文件
//顯示
defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder
//隱藏
defaults write com.apple.finder AppleShowAllFiles -bool false
killall Finder
  • iOS跳轉(zhuǎn)到App Store下載應(yīng)用評分
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
  • 手動(dòng)更改iOS狀態(tài)欄的顏色
-(void)setStatusBarBackgroundColor:(UIColor *)color
{
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
    {
      statusBar.backgroundColor = color;
    }
}
  • 獲取實(shí)際使用的LaunchImage圖片
-(NSString *)getLaunchImageName
{
    CGSize viewSize = self.window.bounds.size;
    // 豎屏
    NSString *viewOrientation = @"Portrait";
    NSString *launchImageName = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize =     CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImageName = dict[@"UILaunchImageName"];
        }
    }
    return launchImageName;
}
  • 在當(dāng)前屏幕獲取第一響應(yīng)
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
  • 判斷對象是否遵循了某協(xié)議
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
{
    [self.selectedController performSelector:@selector(onTriggerRefresh)];
}
  • 判斷view是不是指定視圖的子視圖
BOOL isView = [textView isDescendantOfView:self.view];
  • NSArray 快速求總和 最大值 最小值 和 平均值
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
  • 修改UITextField中Placeholder的文字顏色
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
  • 關(guān)于NSDateFormatter的格式
G: 公元時(shí)代递胧,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,顯示為1-12
MMM: 月,顯示為英文月份簡寫,如 Jan
MMMM: 月尚猿,顯示為英文月份全稱,如 Janualy
dd: 日楣富,2位數(shù)表示凿掂,如02
d: 日,1-2位顯示纹蝴,如 2
EEE: 簡寫星期幾缠劝,如Sun
EEEE: 全寫星期幾,如Sunday
aa: 上下午骗灶,AM/PM
H: 時(shí)惨恭,24小時(shí)制,0-23
K:時(shí)耙旦,12小時(shí)制脱羡,0-11
m: 分,1-2位
mm: 分免都,2位
s: 秒锉罐,1-2位
ss: 秒,2位
S: 毫秒
  • 獲取一個(gè)類的所有子類
+(NSArray *) allSubclasses
{
    Class myClass = [self class];
    NSMutableArray *mySubclasses = [NSMutableArray array];
    unsigned int numOfClasses;
    Class *classes = objc_copyClassList(&numOfClasses;);
    for (unsigned int ci = 0; ci < numOfClasses; ci++)
    {
        Class superClass = classes[ci];
        do{
            superClass = class_getSuperclass(superClass);
        } while (superClass && superClass != myClass);
        if (superClass)
        {
            [mySubclasses addObject: classes[ci]];
        }
    }
    free(classes);
    return mySubclasses;
}
  • 監(jiān)測設(shè)備是否設(shè)置了代理绕娘,需要CFNetwork.framework
NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
NSLog(@"\n%@",proxies);
NSDictionary *settings = proxies[0];
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);
if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"])
{
NSLog(@"沒代理");
}
else
{
NSLog(@"設(shè)置了代理");
}
  • 取消UICollectionView的隱式動(dòng)畫

UICollectionView在reloadItems的時(shí)候脓规,默認(rèn)會(huì)附加一個(gè)隱式的fade動(dòng)畫,有時(shí)候很討厭险领,尤其是當(dāng)你的cell是復(fù)合cell的情況下(比如cell使用到了UIStackView)侨舆。
下面幾種方法都可以幫你去除這些動(dòng)畫

//方法一
[UIView performWithoutAnimation:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
}];
//方法二
[UIView animateWithDuration:0 animations:^{
[collectionView performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:nil];
}];
//方法三
[UIView setAnimationsEnabled:NO];
[self.trackPanel performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:^(BOOL finished) {
[UIView setAnimationsEnabled:YES];
}];
  • 讓Xcode的控制臺支持LLDB類型的打印

打開終端輸入三條命令:

touch ~/.lldbinit
echo display @import UIKit >> ~/.lldbinit
echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit
  • CocoaPods pod install/pod update更新慢的問題
pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加后面的參數(shù),默認(rèn)會(huì)升級CocoaPods的spec倉庫绢陌,加一個(gè)參數(shù)可以省略這一步挨下,然后速度就會(huì)提升不少
  • GCD timer定時(shí)器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒執(zhí)行
dispatch_source_set_event_handler(timer, ^{
    //@"倒計(jì)時(shí)結(jié)束,關(guān)閉"
    dispatch_source_cancel(timer);
    dispatch_async(dispatch_get_main_queue(), ^{
    });
});
dispatch_resume(timer);
  • 禁用UIWebView的默認(rèn)交互行為
public func webViewDidFinishLoad(webView: UIWebView) {
        if disableUserSelect { // 禁用用戶選擇
          webView.stringByEvaluatingJavaScriptFromString("document.documentElement.style.webkitUserSelect='none';")
        }
        if disableLongTouch { // 禁用長按彈出框
          webView.stringByEvaluatingJavaScriptFromString("document.documentElement.style.webkitTouchCallout='none';")
        }
}
  • UIButton 移除所有事件
button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
  • 在模擬器中添加視頻
//Add a video in Simulator
if let a = NSBundle.mainBundle().pathForResource("test", ofType: "mov", inDirectory: nil) {
    UISaveVideoAtPathToSavedPhotosAlbum(a, self, nil, nil)
}
  • 液晶時(shí)鐘字體
label.font=[UIFont fontWithName:@"DBLCDTempBlack" size:60.0];
  • UIAlertController改變按鈕文字顏色
alertC.view.tintColor = your color;
//setting the tintColor after presenting the controller works on both iOS 8 and 9

問題集錦

  • Can't add self as subview

iOS7剛發(fā)布的時(shí)候脐湾,總是出現(xiàn)這個(gè) Can't add self as subview 的崩潰臭笆,異常描述和崩潰堆棧是這樣的:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't add self as subview' 

這是因?yàn)閷?dǎo)航欄在做動(dòng)畫的時(shí)候,執(zhí)行了一次[self addSubView:self]
為了防止這種情況秤掌,我們在UINavigationController基類中加入防御愁铺,具體做法是在push,pop方法中設(shè)置一個(gè)標(biāo)志位(animating=YES)闻鉴,在動(dòng)畫結(jié)束之后茵乱,再重置這個(gè)標(biāo)志位,然后椒拗,用這個(gè)標(biāo)志位判斷push和pop操作是否能夠執(zhí)行似将。

@interface UIViewController (Animating)
@property (nonatomic, assign) BOOL animating;
@end
@implementation BaseNavigationController
-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (topVC.animating) {
        return;
    }
    topVC.animating = YES;
    viewController.animating = YES;
    [super pushViewController:viewController animated:animated];
}
@end
@implementation BaseKitViewController
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.animating = NO;
}
-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.animating = NO;
}
@end
  • TestFlight上傳不成功提示ITSAppUsesNonExemptEncryption

info.plist添加下面鍵值對

<key>ITSAppUsesNonExemptEncryption</key><false/>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末获黔,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子在验,更是在濱河造成了極大的恐慌玷氏,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件腋舌,死亡現(xiàn)場離奇詭異盏触,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)块饺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進(jìn)店門赞辩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人授艰,你說我怎么就攤上這事辨嗽。” “怎么了淮腾?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵糟需,是天一觀的道長。 經(jīng)常有香客問我谷朝,道長洲押,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任圆凰,我火速辦了婚禮杈帐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘专钉。我一直安慰自己挑童,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布驶沼。 她就那樣靜靜地躺著炮沐,像睡著了一般争群。 火紅的嫁衣襯著肌膚如雪回怜。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天换薄,我揣著相機(jī)與錄音玉雾,去河邊找鬼。 笑死轻要,一個(gè)胖子當(dāng)著我的面吹牛复旬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播冲泥,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼驹碍,長吁一口氣:“原來是場噩夢啊……” “哼壁涎!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起志秃,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤怔球,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后浮还,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體竟坛,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年钧舌,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了担汤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,615評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡洼冻,死狀恐怖崭歧,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情撞牢,我是刑警寧澤驾荣,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站普泡,受9級特大地震影響播掷,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜撼班,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一歧匈、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧砰嘁,春花似錦件炉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至缅阳,卻和暖如春磕蛇,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背十办。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工秀撇, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人向族。 一個(gè)月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓呵燕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親件相。 傳聞我的和親對象是個(gè)殘疾皇子再扭,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評論 2 359

推薦閱讀更多精彩內(nèi)容