2019年6月11日 星期二

obj-c 保護你的delegate method calling


@protocol SearchViewDelegate<NSObject>

@optional
- (void)searchTextFieldDidBeginEditing;
- (void)onSearchTextFieldValueChanged:(NSString *)text;
@end


@interface SearchView()


@end


@implementation SearchView
typedef struct {
    unsigned int searchTextFieldDidBeginEditing:1;
    unsigned int onSearchTextFieldValueChanged:1;
} DelegateRespondsTo;
DelegateRespondsTo delegateRespondsTo;

- (void)setDelegate:(id <SearchViewDelegate>)aDelegate {
    if (_delegate != aDelegate) {
        _delegate = aDelegate;
        
        delegateRespondsTo.searchTextFieldDidBeginEditing = [_delegate respondsToSelector:@selector(searchTextFieldDidBeginEditing)];
        delegateRespondsTo.onSearchTextFieldValueChanged = [_delegate respondsToSelector:@selector(onSearchTextFieldValueChanged:)];
    }
}

2019年5月7日 星期二

textFieldShouldClear dismiss keyboard

func textFieldShouldClear(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()
        
    textField.text = nil
        
    return false
}

2019年4月8日 星期一

改變UISegmentedControl的font

#import "UISegmentedControl+Font.h"

@implementation UISegmentedControl(Font)

- (void)setFont:(UIFont *)font color:(UIColor *)color {
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, [UIColor blackColor], NSForegroundColorAttributeName, nil];
    [self setTitleTextAttributes:attributes forState:UIControlStateNormal];
    NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    [self setTitleTextAttributes:highlightedAttributes forState:UIControlStateSelected];
}

@end

2018年12月14日 星期五

better way 更新tableview

當你一個小改變要更新cell的時候,reloadData 會導致很大的效能浪費,更慘的是tableview會有不必要的動畫被看到。

有一種解法是放delegate去給tableviewcell執行,這樣不用重繪tableview的整個cell,但還是會給所有的cell執行一次。

更好的作法是先更新tableview data,但不去reloadData,然後只更新看得見的部份
for (EmployeeListTableViewCell *cell in self.tableView.visibleCells) {
            //TODO: update the UI
}
剩下的交給tableView自己,在滑動到其他cell的時候更新。

2018年11月6日 星期二

UIApplicationWillChangeStatusBarOrientationNotification v.s. UIApplicationDidChangeStatusBarOrientationNotification


結論:
UIApplicationWillChangeStatusBarOrientationNotification
會先被呼叫,而且userInfo 是傳送將要轉換的 orientation。

UIApplicationDidChangeStatusBarOrientationNotification
後被呼叫,但userInfo是傳送轉換前的 orientation。

code:

    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(statusOrientationWillChange:)
                                               name:UIApplicationWillChangeStatusBarOrientationNotification object:nil];
   
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(statusOrientationDidChange:)
                                               name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];

- (void)statusOrientationWillChange:(NSNotification *)notification {
    if (notification.userInfo != nil && notification.userInfo[UIApplicationStatusBarOrientationUserInfoKey] != nil) {
        UIInterfaceOrientation orientation = (UIInterfaceOrientation)[(NSNumber *)notification.userInfo[UIApplicationStatusBarOrientationUserInfoKey] integerValue];
        if (UIInterfaceOrientationIsLandscape(orientation)) {
            self.isLandscape = YES;
        } else {
            self.isLandscape = NO;
        }
    }
   
    [self.tableView reloadData];
}

- (void)statusOrientationDidChange:(NSNotification *)notification {
    if (notification.userInfo != nil && notification.userInfo[UIApplicationStatusBarOrientationUserInfoKey] != nil) {
        UIInterfaceOrientation orientation = (UIInterfaceOrientation)[(NSNumber *)notification.userInfo[UIApplicationStatusBarOrientationUserInfoKey] integerValue];
        if (UIInterfaceOrientationIsLandscape(orientation)) {
            self.isLandscape = YES;
        } else {
            self.isLandscape = NO;
        }
    }
   
}

Strange thing: A - 2 > 0 is not equvalent to A > 2

(lldb) po self.customFields.count - 2 > 0
true

(lldb) po self.customFields.count > 2
false

(lldb) po self.customFields
<__NSArrayM 0x108e54540>(

)

(lldb) po self.customFields.count
<nil>

2018年11月2日 星期五

reuse custom tableview cell

當你用dynamic style cell的時候
所有關於cell的改變都要基於cell source
所以最好的方式就是直接create a Class for table view source
讓整個改動都變得有彈性
不要直接去改當下那個cell,那是不合邏輯的,而且你會修bug修不完
例如,你從coredate的一個表中拿到資料,不要直接拿來用
創一個class去包它,這個class可以自由加入你要的其他設定給你的custom table cell

2018年10月18日 星期四

提早拿到constraint後的frame

加入viewDidLoad可以拿到autolayout後的正確frame

加在animation中,可以在autolayout的情況下作用
[UIView animateWithDuration:0.5 animations:^{
            self.filterViewWidthConstraint.constant = 200;
            [self.view layoutIfNeeded];
        }];

用pdf取代png

在asset中放入pdf,設成all scale,可以用來取代svg當作向量圖。

如果是icon的話,還可以設成templete,可以用tintColor來改變icon的顏色。

超級實用的小技巧

2018年10月15日 星期一

Add touch began to pan gesture

!!!!!!一定要做#import "UIPanGestureRecognizerSubclass.h"
然後用category或是subclass去設定這個state,
才能用readwrite不然,原本的recognizer是readonly










@interface TouchableImageView:UIImageView
@property(strong, nonatomic) UIPanGestureRecognizer *panGR; // 這裡要改成自己的recognizer或是實作一個category
@end

@implementation TouchableImageView
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.panGR.state = UIGestureRecognizerStateBegan;
}
@end
//直接改狀態就能trigger gesture的began!!

2018年9月24日 星期一

用自己的dependency專案到cocoapods中

我送了一個pull request 到starscream,增加了支援http proxy的功能,
但遲遲沒有人審核,這時只好在專案中使用用自己的github上的版本。
問題是startcream只是Socket.IO-clinet這個專案的dependent project,
而Podfile不支援更來url來使用你自己project來作為其他專案dependent project。

所以我必須要在podfile中取消dependency再把二個專案都加入pods
建好xcworkspace檔案之後,再手動修改pod.xcodeproj來連Socket.IO-clinet使用starscream來build
  1. 去Socket.IO-clinet的project
  2. 去Build Phases
  3. 在Target Dependencies 中加入starscream
  4. 在Link Binary With Libraries 加入 starscream
  5. 最重要的是在Build Settings中把Framework Search Paths中把starscream的位置"$PODS_CONFIGURATION_BUILD_DIR/Starscream"加進去 (記得要在上面選到All才看得到這個設定)
P.S.
另一個方式是把starscream設為private pod,然後用podfile就可以取得。

2018年7月1日 星期日

predicateWithFormat在比對NSNumber的坑

環境: iOS SDK9
在你想比對NSNumber時,從JSON轉出來的數值出現了NSTaggedPointerString,你會比對不到,於是得到nil.
- (Visitor *)visitorByID:(NSNumber *)uid {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Visitor" inManagedObjectContext:self.managedObjectContext]];
   
    if ([uid isKindOfClass:[NSNumber class]]) {
        [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"self.visitor_id == %@", uid]];
    } else {
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        NSNumber *numUid = [numberFormatter numberFromString:(NSString *)uid];
        [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"self.visitor_id == %@", numUid]];
    }
       
        NSError * error = nil;
        NSArray * result = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
       
        if (error!=nil) {
            SOLogError(@"%s[%d:%s]: %@", __FILE__, __LINE__, __FUNCTION__,error.localizedDescription);
        }
}

解法:
把NSTaggedPointerString再轉回NSNumber一次
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *numUid = [numberFormatter numberFromString:(NSString *)uid];

CoreData的performBlock和performBlockAndWait的差異

performBlock
會異步執行在context的thread之中(不會阻塞當前的thread)


performBlockAndWait


會同步執行在context的thread之中(會阻塞當前的thread,直到執行完block中的code再返回)


NSManagedObjectContext save()

https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext/1506866-save
https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext/1506954-haschanges


2018年6月28日 星期四

[array copy] 和 [NSArray arrayWithArray:array] 的異同

// https://segmentfault.com/q/1010000003854902
如果array是immutable类型的NSArray
  • copy只是retain,没有创建新对象
  • arrayWithArray 创建了新的NSArray对象,并将原有数组元素填充进去,数组元素还是原来的对象
如果array是mutable类型的NSArray
  • 二者最终结果是等效的,创建了新的NSArray对象,但数据元素还是原来的对象
如果array == nil
  • copy的结果是nil
  • arrayWithArray 结果是长度为0的NSArray对象
无论哪种情况,数组元素都是共享的 不会被复制

2018年6月12日 星期二

nslog to file

- (void)redirectLogToDocuments {
    NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [allPaths objectAtIndex:0];
    NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"logFile.txt"];
  
    if ([[NSFileManager defaultManager] fileExistsAtPath:pathForLog]) {
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:pathForLog error:&error];
        if (error!=nil) {
            NSLog(@"%@", error.localizedDescription);
        }
    }
    freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

讓圖示在AttributedText上下置中


https://stackoverflow.com/questions/26105803/center-nstextattachment-image-next-to-single-line-uilabel




let iconImage = UIImage(named: "icon.png")!
var icon = NSTextAttachment()
icon.bounds = CGRect(x: 0, y: (titleFont.capHeight - iconImage.size.height).rounded() / 2, width: iconImage.size.width, height: iconImage.size.height)
icon.image = iconImage
let iconString = NSAttributedString(attachment: icon)
titleText.append(iconString)

2018年6月8日 星期五

rate the app

- (IBAction)rateButtonTapped:(UIButton *)sender {
    if (@available(iOS 10.3, *)) {
        [SKStoreReviewController requestReview];
    } else {
        NSURL *url = [NSURL URLWithString:@"itms-apps://itunes.apple.com/tw/app/swipedon-visitor-management/id986185962?l=en&mt=8"];
        [[UIApplication sharedApplication] openURL:url];
    }
}

2018年6月5日 星期二

用CoreData存圖片

不要用core data存圖
是可以轉存NSData去存,但只要你的ManagedObjectContext沒有釋放,那麼那張圖就不會被釋放,如果圖片大一點,一下就爆了

用core data存imageName,把圖片存到文件資料夾裡,用imageName去對應,
並且監聽imageName的setter,在改名之前先刪去原來的圖。